转场动画 transitions
前两节,我们学习了怎样基于属性(eg. postion 及 alpha)创建动画,但是如果我们想在增加与删除 view 的时候进行动画该怎么办呢?
本节我们讲讲 transitions 动画,它可以解决上面提出的问题。
transitions 是可以应用于 views 的预定义动画。这些预定义动画不会尝试在视图的开始和结束状态之间插入。相反,我们可以自定义动画,使状态的各种变化显得优雅自然。
要使屏幕上添加的新视图具有动画效果,可以调用像 addSubview(view) 这样的方法。然而使用转场动画的不同之处在于,我们可以选择一个预定义的转场效果,并将其作用于 animation container view 。
当转场动画执行时,容器视图及其子视图具有动画效果。
var animationContainerView: UIView!
override func viewDidLoad() {
super.viewDidLoad() //set up the animation container
animationContainerView = UIView(frame: view.bounds)
animationContainerView.frame = view.bounds
view.addSubview(animationContainerView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// create new view
let newView = UIImageView(image: UIImage(named: "banner"))
newView.center = animationContainerView.center
// add the new view via transition
UIView.transition(with: animationContainerView, duration: 0.33,options:
[.curveEaseOut, .transitionFlipFromBottom], animations: {
self.animationContainerView.addSubview(newView)
}, completion: nil)
}
我们调用 transition(with:duration:options:animations:completion:) 创建 transition 动画。
predefined transitions option 有以下几种选择:
- .transitionFlipFromLeft
- .transitionFlipFromRight
- .transitionCurlUp
- .transitionCurlDown
- .transitionCrossDissolve
- .transitionFlipFromTop
- .transitionFlipFromBottom
上面是添加视图示例,如果删除视图,则可以这样:
// remove the view via transition
UIView.transition(with: animationContainerView, duration: 0.33, options:
[.curveEaseOut, .transitionFlipFromBottom], animations: {
self.newView.removeFromSuperview()
}, completion: nil )
Hiding/showing a view 可以这样:
// hide the view via transition
UIView.transition(with: self.newView, duration: 0.33, options: [.curveEaseOut,
.transitionFlipFromBottom], animations: {
self.newView.isHidden = true
}, completion: nil )
Replacing a view with another view 可以这样:
//replace via transition
UIView.transition(from: oldView, to: newView, duration: 0.33, options: .transitionFlipFromTop, completion: nil)
转场动画是 UIKit 中可以创建 3d 动画的唯一方法。
transitions
参考: