iOS 控制器自定义动画跳转方法(模态跳转)
程序员文章站
2023-12-19 11:59:04
参考资料:
apple 开发文档 customizing the transition animations
wwdc 2013 custom transitions...
参考资料:
apple 开发文档 customizing the transition animations
wwdc 2013 custom transitions using view controllers
图例:
跳转的动画有很多,全部可以自定义
创建自定义跳转必须遵循的三个步骤:
1、创建一个类,并实现了 uiviewcontrolleranimatedtransitioning 协议
2、创建一个类作为 uiviewcontrollertransitioningdelegate 过渡代理
3、在模态跳转前修改控制器的 transitioningdelegate 代理为自定义的代理(步骤2的代理类)
核心代码示例
一、创建一个类,并实现了 uiviewcontrolleranimatedtransitioning 协议
这个协议主要控制控制器视图的显示的,通过 transitioncontext 可以获取到每个视图和控制器,并进行动画的设置
class animatedtransitioning: nsobject { var ispresenting: bool = false } extension animatedtransitioning: uiviewcontrolleranimatedtransitioning { func transitionduration(using transitioncontext: uiviewcontrollercontexttransitioning?) -> timeinterval { return 0.5 } func animatetransition(using transitioncontext: uiviewcontrollercontexttransitioning) { let fromview = transitioncontext.view(forkey: .from)! let toview = transitioncontext.view(forkey: .to)! let containerview = transitioncontext.containerview if ispresenting { toview.transform = cgaffinetransform(scalex: 0, y: 0) containerview.addsubview(toview) } else { containerview.insertsubview(toview, belowsubview: fromview) } uiview.animate(withduration: 0.5, animations: { if self.ispresenting { toview.transform = cgaffinetransform.identity } else { fromview.transform = cgaffinetransform(scalex: 0.001, y: 0.001) } }) { (finished) in transitioncontext.completetransition(finished) } } }
二、创建一个类作为 uiviewcontrollertransitioningdelegate 过渡代理
这里设置 presented 和 dismissed 时各自的动画转换类,可以设置为不同的类
class customtransitioningdelegate: nsobject, uiviewcontrollertransitioningdelegate { func animationcontroller(forpresented presented: uiviewcontroller, presenting: uiviewcontroller, source: uiviewcontroller) -> uiviewcontrolleranimatedtransitioning? { let at = animatedtransitioning() at.ispresenting = true return at } func animationcontroller(fordismissed dismissed: uiviewcontroller) -> uiviewcontrolleranimatedtransitioning? { let at = animatedtransitioning() at.ispresenting = false return at } }
三、在模态跳转前修改控制器的 transitioningdelegate 代理为自定义的代理
注意:代理不能为局部变量
class viewcontroller: uiviewcontroller { // 必须保存为实例变量 var ctdelegate = customtransitioningdelegate() override func touchesbegan(_ touches: set<uitouch>, with event: uievent?) { let vc = tempviewcontroller() vc.transitioningdelegate = ctdelegate self.present(vc, animated: true, completion: nil) } }
以上这篇ios 控制器自定义动画跳转方法(模态跳转)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。