Navigation & Modal 自定义转场动画
2023-05-09 本文已影响0人
麦志超
Navigation 转场用法
class LoginViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.delegate = self
}
}
extension LoginViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
return GotoAnimatedTransitioning()
case .pop:
return GoBackAnimatedTransitioning()
default:
return nil
}
}
}
Modal 转场用法
let vc = ForgetPasswordViewController()
vc.transitioningDelegate = self
vc.modalPresentationStyle = .fullScreen
self?.present(vc, animated: true)
extension LoginViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return GotoAnimatedTransitioning()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return GoBackAnimatedTransitioning()
}
}
Push / Present 自定义转场动画
class GotoAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
transitionContext.containerView.addSubview(toViewController.view)
toViewController.view.alpha = 0
toViewController.view.transform = CGAffineTransform(scaleX: 0, y: 0)
let duration = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
toViewController.view.alpha = 1
toViewController.view.transform = .identity
}, completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
Pop / Dismiss 自定义转场动画
class GoBackAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from), let toViewController = transitionContext.viewController(forKey: .to) else {
return
}
transitionContext.containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view)
let duration = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
fromViewController.view.alpha = 0
}, completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}