我学习了如何在ViewController之间创建自定义过渡。根据{{3}}这本书,我有这样的代码:
//FadeAnimator.swift
import UIKit
class FadeAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 1.0
var presenting = true
var originFrame = CGRect.zero
var dismissCompletion: (()->Void)?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
//Setting the transition’s context
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
//Adding a fade transition
let containerView = transitionContext.containerView
let toView = transitionContext.view(forKey: .to)!
containerView.addSubview(toView)
toView.alpha = 0.0
UIView.animate(withDuration: duration,
animations: {
toView.alpha = 1.0
},
completion: { _ in
transitionContext.completeTransition(true)
}
)
}
}
我就这样使用它并且有效:
// Screen3.swift
import UIKit
class Screen3: UIViewController, UINavigationControllerDelegate {
let transition = FadeAnimator()
//happens only once
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Hello World"
view.backgroundColor = .blue
self.navigationController?.delegate = self
}
//happens every time when shown
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupLayout()
}
private func setupLayout() {
....
//btn1.clickHandler {
let nextScreen = Screen4() //4th Screen
nextScreen.transitioningDelegate = self as? UIViewControllerTransitioningDelegate
self.navigationController?.pushViewController(nextScreen, animated: true)
//self.present(nextScreen, animated: true, completion: nil)
//}
....
}
//forward
func animationController(forPresented presented: UIViewController,
presenting: UIViewController, source: UIViewController) ->
UIViewControllerAnimatedTransitioning? {
return transition
}
//backward
func animationController(forDismissed dismissed: UIViewController) ->
UIViewControllerAnimatedTransitioning? {
return nil
}
}
基于另一本教程,我创建了这样的结构:
// Transitions.swift
import UIKit
struct Transitions {
static func setTransitionTo(view: UIView!, from: CATransitionSubtype = .fromRight) {
let transition = CATransition()
transition.duration = 0.5
transition.type = CATransitionType.push
transition.subtype = from //CATransitionSubtype.fromRight
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
}
static func setFadeTransitionTo(view: UIView!) {
//let transition = SKTransition.fade(withDuration: 0.5)
let transition = CATransition()
transition.duration = 0.5
transition.type = CATransitionType.fade
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
}
}
下一个问题是:如何在animateTransition()函数中使用CATransition获得相同的结果?