【Swift学习笔记-《PRODUCT》读书记录-实现自定义转场动画】
生活随笔
收集整理的這篇文章主要介紹了
【Swift学习笔记-《PRODUCT》读书记录-实现自定义转场动画】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
iOS默認的push動畫是把即將展示的控制器從右邊推過來。有時我們想實現類似PPT中的一些動畫,這時候就需要自定義轉場動畫了。如下圖我們想實現一個淡出并且放大的過場動畫,在退出時是一個淡出縮小的動畫。
首先需要自定義一個類DiaryAnimator.swift遵守?UIViewControllerAnimatedTransitioning 協議,然后實現它,代碼如下:
import UIKitclass DiaryAnimator: NSObject, UIViewControllerAnimatedTransitioning {// 用于接受外界的operationvar operation:UINavigationControllerOperation!// 返回動畫時間func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {return 0.4}// 要設置的動畫//UIKit calls this method when presenting or dismissing a view controller. Use this method to configure the animations associated with your custom transition. You can use view-based animations or Core Animation to configure your animations.func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {let containerview = transitionContext.containerViewlet fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)let fromView = fromVC!.viewlet toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)let toView = toVC?.view// 設置新場景透明度toView?.alpha = 0.0// 設置初始值if operation == UINavigationControllerOperation.pop {fromView?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)}else{toView?.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)}containerview.insertSubview(toView!, aboveSubview: fromView!)UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {if self.operation == UINavigationControllerOperation.pop {// 放大要轉出的場景fromView?.transform = CGAffineTransform(scaleX: 3.3,y: 3.3)} else {// 設置新場景為原始大小toView?.transform = CGAffineTransform(scaleX: 1.0,y: 1.0)}toView?.alpha = 1.0},completion: { finished intransitionContext.completeTransition(true)})}}?自定義好動畫后,在要使用的控制器中實現?UINavigationControllerDelegate 協議的?optional func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? 方法,返回自定義的動畫即可
extension HomeYearController : UINavigationControllerDelegate {func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {let animate = DiaryAnimator()animate.operation = operationreturn animate} }?
轉載于:https://www.cnblogs.com/heyode/p/6513581.html
總結
以上是生活随笔為你收集整理的【Swift学习笔记-《PRODUCT》读书记录-实现自定义转场动画】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 66-Flutter移动电商实战-会员中
- 下一篇: 多位大厂专家鼎力推荐,44个微服务架构设