使用UIView动画函数实现转场动画——双视图
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion;
参数说明:
–duration:动画的持续时间
–options:转场动画的类型
–animations:将改变视图属性的代码放在这个block中
–completion:动画结束后,会自动调用这个block
方法调用完毕后,相当于执行了下面两句代码:
// 添加toView到父视图
[fromView.superview addSubview:toView];
// 把fromView从父视图中移除
[fromView removeFromSuperview];
具体实例如下:
实现功能:创建两个子视图view1和view2,分别设置不同的背景颜色,并把它们添加到父视图中,然后创建触摸点击手势,
每次触摸屏幕时,两个视图交替切换显示,即实现转场动画。
代码如下:
//声明属性
#import "ViewController.h" @interface ViewController () @property (strong,nonatomic)UIView *view1; @property (strong,nonatomic)UIView *view2; @end
//初始化,创建两个子视图,同时创建触摸点击手势并添加手势事件
- (void)viewDidLoad { [super viewDidLoad]; //初始化 self.view1 = [[UIView alloc]initWithFrame:self.view.frame]; self.view1.backgroundColor = [UIColor redColor]; //view1背景色为红色 [self.view addSubview:self.view1]; self.view2 = [[UIView alloc]initWithFrame:self.view.frame]; self.view2.backgroundColor = [UIColor greenColor];//view2背景色为绿色 [self.view addSubview:self.view2]; //添加tap手势 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)]; tap.numberOfTapsRequired = 1; tap.numberOfTouchesRequired = 1; [self.view addGestureRecognizer:tap]; }
//处理触摸点击手势事件,在block函数中实现双视图转场动画
#pragma mark -tap手势事件 -(void)tap:(UITapGestureRecognizer *)sender { //通过判断视图的父视图是否为空,可以知道当前视图是不是正在显示 if (self.view2.superview == nil) { //通过block函数切换子视图(设置动画过渡类型为翻书效果) [UIView transitionFromView:self.view1 toView:self.view2 duration:1.0f options:UIViewAnimationOptionTransitionCurlUp completion:nil];; } else { //通过block函数切换子视图(设置动画过渡类型为翻书效果) [UIView transitionFromView:self.view2 toView:self.view1 duration:1.0f options:UIViewAnimationOptionTransitionCurlUp completion:nil]; } }
演示结果如下:
开始时:
点击后:
动画结束后:
还可以接着点击,会变为绿色视图,就不一一演示了。
时间: 2024-10-07 18:02:40