Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

画面遷移カスタマイズ

class PushAnimator : NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 1.0
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromV = transitionContext.view(forKey: .from) else {
            return
        }
        guard let toV = transitionContext.view(forKey: .to) else {
            return
        }
        
        let container = transitionContext.containerView
        container.insertSubview(toV, belowSubview: fromV)
        
        UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
                       animations: {
                        fromV.alpha = 0.0
        },
                       completion: { finished in
                        fromV.alpha = 1.0
                        toV.alpha = 1.0
                        transitionContext.completeTransition(finished)
        })
        
    }
}

とやって、ナビゲーションのデリゲートに

    // 画面遷移
    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationControllerOperation,
                              from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = PushAnimator()
        switch operation {
        case .pop,.push:
            return animator
        case .none:
            return nil
        }
    }