自定义不改变frame
的转场动画只需要两步:
- 自定义转场动画类
- 设置转场代理
一, 自定义转场动画类
class CustomAnimation: NSObject {}
二, 设置转场代理
showVC.modalPresentationStyle = .custom // 背景视图不被删除
showVC.transitioningDelegate = customAnimation // 代理动画UIViewControllerTransitioningDelegate协议
// 其中,customAnimation 是一个懒加载属性,private lazy var customAnimation = CustomAnimation()
1,在自定义转场动画类中,需要遵守UIViewControllerTransitioningDelegate
协议:
//MARK: - 设置转场代理
extension CustomAnimation:UIViewControllerTransitioningDelegate{
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// 弹出之后做事情
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// 消失之后做事情
return self
}
}
2,由于上方法return self,所以需要遵守UIViewControllerAnimatedTransitioning
协议
//MARK: - 自定义动画属性
extension CustomAnimation:UIViewControllerAnimatedTransitioning{
// 1 动画时长
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
// 2 设置点击之后是弹出 还是 消失
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPresent ? animationPresentedView(transitionContext: transitionContext) : animationDismissedView(transitionContext: transitionContext)
}
func animationPresentedView(transitionContext: UIViewControllerContextTransitioning) {
// 1 取出显示视图
let presentView = transitionContext.view(forKey: .to)
// 2 添加到containerView
transitionContext.containerView.addSubview(presentView!);
// 3 添加动画
presentView?.alpha = 0.0
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
presentView?.alpha = 1.0
}) { (_) in
dismissView?.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
func animationDismissedView(transitionContext: UIViewControllerContextTransitioning) {
// 1 取出消失视图
let dismissView = transitionContext.view(forKey: .from)
// 2 添加动画
dismissView?.alpha = 1.0
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
dismissView?.alpha = 0.0
}) { (_) in
transitionContext.completeTransition(true)
}
}
}
网友评论