在我们的UI设计中实现友好的界面设计和动态的效果会更加的吸引用户,在iOS中提供了丰富的转场动画,下面就简单的介绍一下。
转场动画的简单介绍:
CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果。iOS比Mac OS X的转场动画效果少一点,UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果
一、转场动画实现 UIView动画
属性解析:
type:动画过渡类型
subtype:动画过渡方向
startProgress:动画起点(在整体动画的百分比)
endProgress:动画终点(在整体动画的百分比)
1、转场动画过滤效果类型字符串如下图所示:
2、我们实现4张图片的切换有上述类型的代码段
{
if( i == 4)
{
i = 1;
}
NSString *imageName = [NSString stringWithFormat:@"%d",i];
//过渡代码和转场代码放在一起
self.imageView.image = [UIImage imageNamed:imageName];
i++;
CATransition *anim = [CATransition animation];
anim.type = @"cameraIrisHollowClose";
anim.duration = 2;
//设置动画进度
anim.startProgress = 0.5;
[self.imageView.layer addAnimation:anim forKey:nil];
二、modal控制器实现转场动画
1、遵守UIViewControllerAnimatedTransitioning 和
/// 返回提供转场动画的遵守 `UIViewControllerAnimatedTransitioning` 协议的对象
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
/// 返回提供解除转场的对象
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
2、控制器遵守UIViewControllerAnimatedTransitioning ,
// 转场动画时长
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 2.0
}
// 自定义转场动画 - 只要实现了此方法,就需要自己来动画代码
/**
transitionContext 提供了转场动画需要的元素
completeTransition(true) 动画结束后必须调用的
containerView() 容器视图
viewForKey 获取到转场的视图
*/
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
print(fromVC)
print(toVC)
// Modal
if isPresented {
// 展现动画
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
// 将目标视图,添加到容器视图中
transitionContext.containerView()?.addSubview(toView)
toView.alpha = 0
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
toView.alpha = 1.0
}) { (_) -> Void in
// 动画结束之后,一定要执行,如果不执行,系统会一直等待,无法进行后续的交互!
transitionContext.completeTransition(true)
}
} else {
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
fromView.alpha = 0.0
}, completion: { (_) -> Void in
fromView.removeFromSuperview()
// 解除转场时,会把 容器视图以及内部的内容一起销毁
transitionContext.completeTransition(true)
})
}