Swift 优化自定义转场的菜单

通常情况下 模态弹出的控制器是从底部向上弹出的 如果想要实现从顶部慢慢向下展开的效果 就在UIViewControllerTransitioningDelegate中,重写animationForPresentedController 和 animationControllerForDismissedController方法,分别负责转场如何出现和消失

func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) ->  UIViewControllerAnimatedTransitioning? {

return self


}

func animationControllerForDismissController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {

return self

}

要实现以上自定义转场动画 须遵守以下协议

extension myViewController : UIViewControllerAnimatedTransitioning {

func transitionDuration(transitionContext: UIViewControllerContextTransition?) -> NSTimeInterval{

//用于告诉系统展现和消失的动画时长

return 3

}

func animateTransition(transitionContext: UIViewControllerContextTransiting){

//专门用于管理modal如何展现和消失的,无论是展现还是消失都调用该方法,只要实现了这个代理方法,那么系统就不会再有默认的动画了 也就是默认的modal从下至上的移动系统不再帮我们添加了,所有的动画操作都需要我们自己实现,包括需要展现的视图也需要我们自己添加到容器视图上

//通过toViewKey取出的就是toVC对应的view

guard let toView = transitionContext.viewControllerForKey(UITransitionContextToViewKey) else {

 return //因为toView是可选值

}

//通过fromViewKey取出的就是fromVC对应的view

let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey  )

//将需要弹出的控制器添加到containerView上

transitionContext.containerView()?.addSubview(toView)

//执行动画 向下展开

toView.transform = CGAffineTransformMakeScale(1.0, 0.0)

//设置锚点

toView.layer.anchorPoint = CGPoint(x:0.5,y:0)

UIView.animateWithDuration(2.0, animation: { () -> Void in

toView.transform = CGAffineTransformIdentity

}) { (_) -> Void in

transitionContext.completeTransition(true)


}

}

}

你可能感兴趣的:(Swift 优化自定义转场的菜单)