轉(zhuǎn)場動(dòng)畫 transitions
前兩節(jié),我們學(xué)習(xí)了怎樣基于屬性(eg. postion 及 alpha)創(chuàng)建動(dòng)畫,但是如果我們想在增加與刪除 view 的時(shí)候進(jìn)行動(dòng)畫該怎么辦呢?
本節(jié)我們講講 transitions 動(dòng)畫,它可以解決上面提出的問題。
transitions 是可以應(yīng)用于 views 的預(yù)定義動(dòng)畫。這些預(yù)定義動(dòng)畫不會(huì)嘗試在視圖的開始和結(jié)束狀態(tài)之間插入阎毅。相反,我們可以自定義動(dòng)畫栋猖,使?fàn)顟B(tài)的各種變化顯得優(yōu)雅自然净薛。
要使屏幕上添加的新視圖具有動(dòng)畫效果,可以調(diào)用像 addSubview(view) 這樣的方法蒲拉。然而使用轉(zhuǎn)場動(dòng)畫的不同之處在于,我們可以選擇一個(gè)預(yù)定義的轉(zhuǎn)場效果燃领,并將其作用于 animation container view 锦援。
當(dāng)轉(zhuǎn)場動(dòng)畫執(zhí)行時(shí),容器視圖及其子視圖具有動(dòng)畫效果曼库。
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)
}
我們調(diào)用 transition(with:duration:options:animations:completion:) 創(chuàng)建 transition 動(dòng)畫毁枯。
prede?ned 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)
轉(zhuǎn)場動(dòng)畫是 UIKit 中可以創(chuàng)建 3d 動(dòng)畫的唯一方法种玛。
參考: