iOS9中將轉(zhuǎn)場動畫和ViewController剝離,可以自定義Segue,從而復(fù)用.
Segues默認(rèn)有幾種方式:
- Show: 從Navigation Controller push一個頁面.
- Show Detail: 向上彈出一個新的頁面.
- Present Modally: 在當(dāng)前頁面覆蓋一個新的頁面.
- Popover: iPad彈出個小界面iPhone全屏以Model形式彈出一個界面.
- Custom:自定義Segue
關(guān)于不同Segue的區(qū)別和用法可以參考這里 那里和最后這篇
iOS8中已經(jīng)不建議使用以前Segue的Push Modal Popover和Replace了.
我們要來創(chuàng)建一個如下圖的轉(zhuǎn)場效果:
Segue有三個重要的協(xié)議:
- UIViewControllerTransitioningDelegate
- UIViewControllerAnimatedTransitioning
- UIViewControllerContextTransitioning
我們創(chuàng)建一個ScaleSegue文件:
class ScaleSegue: UIStoryboardSegue {
override func perform() {
destinationViewController.transitioningDelegate = self
super.perform()
}
}
定義轉(zhuǎn)場動畫:
extension ScaleSegue: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController,
presentingController presenting: UIViewController,
sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ScalePresentAnimator()
}
}
class ScalePresentAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 2.0
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
if let fromNC = fromViewController as? UINavigationController {
if let controller = fromNC.topViewController {
fromViewController = controller
}
}
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
if let toView = toView {
transitionContext.containerView()?.addSubview(toView)
}
var startFrame = CGRect.zero
if let fromViewController = fromViewController as? ViewScaleable {
startFrame = fromViewController.scaleView.frame
} else {
print("Warning: Controller \(fromViewController) does not conform to ViewScaleable")
}
toView?.frame = startFrame
toView?.layoutIfNeeded()
let duration = transitionDuration(transitionContext)
let finalFrame = transitionContext.finalFrameForViewController(toViewController)
UIView.animateWithDuration(duration, animations: {
toView?.frame = finalFrame
toView?.layoutIfNeeded()
fromView?.alpha = 0.0
}, completion: {
finished in
fromView?.alpha = 1.0
transitionContext.completeTransition(true)
})
}
最后設(shè)置下Segue class:
Girl學(xué)iOS100天 第2天
閱讀和寫出來果然不太一樣,現(xiàn)在寫的很費勁,沒多少內(nèi)容,但卻花費了3個番茄鐘的時間,而且質(zhì)量不高,但希望自己能堅持.
很喜歡《賣油翁》的一句話"無他'唯手熟爾",共勉 :)