返回

iOS 开发之 UINavigationController 实现左滑 Push 自定义动画

IOS

引言

在 iOS 应用开发中,UINavigationController 是一种常见的导航控制器,用于管理应用中的视图层次结构。为了提升用户体验,开发者常常需要对 UINavigationController 的默认行为进行自定义,例如实现全屏 Pop 动画或自定义 Push 动画。

实现左滑 Push 自定义动画

要实现左滑 Push 自定义动画,我们需要覆盖 UINavigationController 的 pushViewController(_:animated:) 方法,并在此方法中添加自定义动画。具体步骤如下:

  1. 创建自定义动画对象 :创建一个自定义动画类,该类遵循 UIViewControllerAnimatedTransitioning 协议。此类负责定义动画的持续时间和过渡效果。

  2. 实现协议方法 :实现 UIViewControllerAnimatedTransitioning 协议中定义的两个方法:transitionDuration(_:)animateTransition(_:)transitionDuration(_:) 方法指定动画的持续时间,而 animateTransition(_:) 方法负责执行实际的动画。

  3. 添加自定义动画 :在 animateTransition(_:) 方法中,使用 UIView 的动画 API(如 UIView.animate(withDuration:animations:))添加自定义动画。例如,您可以为 Push 操作定义一个向左滑动的动画。

  4. 设置自定义动画 :在覆盖的 pushViewController(_:animated:) 方法中,将自定义动画对象作为第二个参数传递给 navigationController.pushViewController(_:animated:) 方法。

示例代码

以下代码示例展示了如何实现一个左滑 Push 自定义动画:

class LeftSwipePushAnimator: NSObject, UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let toViewController = transitionContext.viewController(forKey: .to),
            let toView = transitionContext.view(forKey: .to) else {
                return
        }

        let containerView = transitionContext.containerView
        let finalFrame = transitionContext.finalFrame(for: toViewController)

        toView.frame = finalFrame.offsetBy(dx: -containerView.bounds.width, dy: 0)

        containerView.addSubview(toView)

        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            toView.frame = finalFrame
        }, completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
    }
}

extension UINavigationController {

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)

        if animated {
            let animator = LeftSwipePushAnimator()
            delegate?.navigationController?(self, animationControllerForOperation: .push, from: topViewController, to: viewController) ?? animator
        }
    }
}

注意事项

在实现自定义动画时,需要注意以下几点:

  • 性能优化 :确保动画高效且流畅,避免对应用性能造成负面影响。
  • 用户体验 :动画应符合用户预期,并提供良好的交互体验。
  • 测试覆盖 :编写单元测试以确保动画在各种情况下都能正常工作。

结语

通过覆盖 UINavigationController 的 pushViewController(_:animated:) 方法并添加自定义动画,我们可以实现左滑 Push 自定义动画。这可以增强用户体验,并在需要时为应用添加视觉吸引力。在实施此类动画时,请务必考虑性能优化、用户体验和测试覆盖等因素。