CATransition基础

简介

CATransition通常用于通过CALayer控制UIView子控件过渡动画,比如删除子控件添加子控件切换两个子控件等。

基本使用

  1. 创建CATransition对象。
  2. CATransition设置typesubtype两个属性,type指定动画类型,subtype指定动画移动方向(有些动画是固定方向,指定subtype无效)。
  3. 如果不需要动画执行整个过程(动画执行到中间部分就停止),可以指定startProgressendProgress属性。
  4. 调用UIViewlayer属性的addAnimation: forKey:方法控制该UIView内子控件的过渡动画。

动画类型

CATransitiontype有以下几个值

kCATransitionFade 渐变
kCATransitionMoveIn 覆盖
kCATransitionPush 推出
kCATransitionReveal 揭开

除此之外,该type还支持如下私有动画

cube 立方体旋转
suckEffect  收缩动画
oglFlip  翻转
rippleEffect  水波动画
pageCurl  页面揭开
pageUnCurl 放下页面
cemeraIrisHollowOpen  镜头打开
cameraIrisHollowClose 镜头关闭

CATransition的subtype属性用于控制动画方向,支持如下值

kCATransitionFromRight
kCATransitionFromLeft
kCATransitionFromTop
kCATransitionFromBottom

更简单的动画方式

使用UIViewbeginAnimations: context:commitAnimations方法来创建动画可以实现类似的效果并且更加方便,具体参考示例中的add方法,能实现的动画有以下几种

typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
    UIViewAnimationTransitionNone,//无动画
    UIViewAnimationTransitionFlipFromLeft,//和oglFlip效果一样
    UIViewAnimationTransitionFlipFromRight,//和oglFlip效果一样
    UIViewAnimationTransitionCurlUp,//和pageCurl效果一样
    UIViewAnimationTransitionCurlDown,//和pageUnCurl效果一样
};

示例

@interface ViewController ()
{
    UILabel *labelA, *labelB;//过渡动画的两个控件
    UIView *containerView;//包含过渡动画的控件,动画的执行者
}

@implementation ViewController
- (void)viewDidLoad {
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, 200)];
    [self.view addSubview:containerView];
    //
    labelA = [[UILabel alloc] initWithFrame:containerView.bounds];
    [containerView addSubview:labelA];
    labelB = [[UILabel alloc] initWithFrame:containerView.bounds];
    [containerView addSubview:labelB];
}

- (void)move
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.25;
    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;
    [containerView.layer addAnimation:transition forKey:nil];
    [containerView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}

//私有动画
- (void)cube
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.25;
    transition.type = @"cube";
    transition.subtype = kCATransitionFromTop;
    [containerView.layer addAnimation:transition forKey:nil];
    [containerView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}

- (void)add
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:1.0f];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:containerView cache:YES];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [containerView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    
    [UIView commitAnimations];
}

你可能感兴趣的:(CATransition基础)