You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改ViewController的NavigationBar在页面弹出时的动画效果

导航栏跟随页面整体右侧滑入实现方案

你遇到的导航栏单独从顶部弹出的问题,本质是自定义转场时只修改了内容ViewController的动画逻辑,没有把导航栏所在的UINavigationController整体纳入动画范围,按以下步骤调整即可实现预期效果:
预期动画效果

1. 明确转场动画作用对象

不要单独给内容ViewController设置动画控制器,需要将承载内容的UINavigationController作为自定义转场的作用对象,让导航栏和内容视图作为整体参与动画。

2. 实现自定义动画控制器

遵守UIViewControllerAnimatedTransitioning协议,在动画方法中直接操作导航控制器的整体视图:

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    let container = transitionContext.containerView
    // 获取待弹出的导航控制器实例
    guard let toNav = transitionContext.viewController(forKey: .to) as? UINavigationController else {
        transitionContext.completeTransition(false)
        return
    }
    // 初始位置设置在屏幕右侧
    let finalFrame = transitionContext.finalFrame(for: toNav)
    toNav.view.frame = finalFrame.offsetBy(dx: UIScreen.main.bounds.width, dy: 0)
    container.addSubview(toNav.view)
    
    // 执行滑入动画
    UIView.animate(withDuration: 0.3) {
        toNav.view.frame = finalFrame
    } completion: { finish in
        transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
    }
}

// 返回动画时长
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return 0.3
}

3. 绑定转场代理

弹出导航控制器前,给UINavigationController实例设置transitioningDelegate为你实现了转场协议的对象,如果是push场景,则设置UINavigationControllerDelegate并在对应的代理方法中返回自定义动画控制器即可。

内容的提问来源于stack exchange,提问作者Gabe Spound

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 03:03:00