美文网首页
Swift自定义转场动画

Swift自定义转场动画

作者: 越天高 | 来源:发表于2020-04-29 15:36 被阅读0次

有些时候我们专场的时候系统默认的style并不能很好的满足我们的需求,这时候我们就需要自定义转场动画

  • 使用
    //1. 创建控制器
        let showPhotoVc = PhotoBrowserVC(indexPath: indexPath as! NSIndexPath, urls: urls as! [URL])
        //2. 设置modal样式
        showPhotoVc.modalPresentationStyle = .custom
        //设置装厂动画代理
        showPhotoVc.transitioningDelegate = 自定义的专场动画

        present(showPhotoVc, animated: true, completion: nil)
  • 自定义一个类
import UIKit

class PhotoBrowserAnimator: NSObject
{
    var isPresent : Bool = false
    
    
}
 //MARK:- TransitioningDelegate -
extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate
{
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
         isPresent = true
        return self as UIViewControllerAnimatedTransitioning
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self as UIViewControllerAnimatedTransitioning
    }
}


extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning
{
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        //执行的时间
        return 1.0
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning)
    {
        isPresent ? animatorForPresentView(transitioningContext: transitionContext) : animatorForDismissView(transitioningContext: transitionContext)
    }
    
    //出现时候的动画
    func animatorForPresentView(transitioningContext : UIViewControllerContextTransitioning)
    {
      //1.取出弹出的View
        let  presentedView = transitioningContext.view(forKey: UITransitionContextViewKey.to)!
        // 2.将prensentedView添加到containerView中
        transitioningContext.containerView.addSubview(presentedView)
        
        //3. 执行f动画
        presentedView.alpha = 0.0
        UIView.animate(withDuration: transitionDuration(using: transitioningContext), animations:
        {
            presentedView.alpha = 1.0
            
        }) { (_) in
            transitioningContext.completeTransition(true)
        }
        
        
    }
    
    //消失时候的动画
    func animatorForDismissView(transitioningContext : UIViewControllerContextTransitioning)
    {
        //1.取出消失的View
        let  dismissView = transitioningContext.view(forKey: UITransitionContextViewKey.from)!
        
        //3. 执行消失动画
        UIView.animate(withDuration: transitionDuration(using: transitioningContext), animations:
        {
            dismissView.alpha = 0.0
            
        }) { (_) in
            dismissView.removeFromSuperview()
            transitioningContext.completeTransition(true)
        }
        
    }
  }

相关文章

网友评论

      本文标题:Swift自定义转场动画

      本文链接:https://www.haomeiwen.com/subject/aaxnwhtx.html