您的位置:首页 > 移动开发 > Swift

【Swift】IOS开发中自定义转场动画

2015-05-24 13:58 525 查看
在IOS开发中,我们model另外一个控制器的时候,一般都使用默认的转场动画。

其实我们可以自定义一些转场动画。达到不同的转场效果。

步骤如下:(photoBrowser是目标控制器)

1.在源控制器中,设置目标控制器的转场代理为 self

//设置Model转场代理
photoBrowser.transitioningDelegate = self


2.同时设置目标控制器的model类型

//设置Model类型
photoBrowser.modalPresentationStyle=UIModalPresentationStyle.Custom


3.定义一个变量记录转场还是退场 (true为转场,false为退场

var isPersent =  false


4.在源控制器中设置跳转,目标控制器中设置关闭(动画要选择true)

presentViewController(photoBrowser, animated: true) { () -> Void in }
dismissViewControllerAnimated(true){SVProgressHUD.dismiss()}


5.源控制器遵守两个代理

UIViewControllerTransitioningDelegate,

UIViewControllerAnimatedTransitioning

6.源控制器实现2个代理方法

func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
//转场
isPersent = true
//源控制器自己负责转场
return self
}

func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{

//退场
isPersent = false
//源控制器自己负责转场
return self
}


7.源控制器再实现2个代理方法

//转场时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval

//转场上下文,负责转场动画的具体内容
func animateTransition(transitionContext: UIViewControllerContextTransitioning){
//转场动画
if isPersent{
if let toView = transitionContext.viewForKey(UITransitionContextToViewKey){
//将傀儡视图(用于动画时展现的画面)加入containerView()
transitionContext.containerView().addSubview(self.persentedDummyView!)
toView.frame = CGRectZero
self.persentedDummyView?.frame = CGRectZero

UIView.animateWithDuration(2.0, animations: { () -> Void in
self.persentedDummyView?.frame = transitionContext.containerView().frame
toView.frame = UIScreen.mainScreen().bounds
}, completion: { (_) -> Void in
//移除傀儡视图
self.persentedDummyView?.removeFromSuperview()
//加入要正常显示的视图
transitionContext.containerView().addSubview(toView)
//结束
transitionContext.completeTransition(true)
})
}
}
//退场动画
if !isPersent{
if let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey){

//隐藏目标控制器
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! HJCPhotoBrowserViewController
fromVC.view.hidden = true
//获得fromVC的快照
let dummy = fromVC.collectionView.visibleCells().last!.snapshotViewAfterScreenUpdates(false)
//将傀儡视图放入containerView
transitionContext.containerView().addSubview(dummy)
//执行动画
UIView.animateWithDuration(2.0, animations: { () -> Void in
dummy.frame = CGRectZero
}, completion: { (_) -> Void in
//移除傀儡视图
dummy.removeFromSuperview()
//结束
transitionContext.completeTransition(true)
})
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐