IOS视图切换的使用
视图切换通过一系列动画效果实现,包括折叠切换、爆炸切换、卡片式切换等等。
修改 ViewController.xib,如下所示
在 xib 中创建按钮的操作
修改 ViewController.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController { UIView *view1; UIView *view2; } -(IBAction)flipFromLeft:(id)sender; -(IBAction)flipFromRight:(id)sender; -(IBAction)flipFromTop:(id)sender; -(IBAction)flipFromBottom:(id)sender; -(IBAction)curlUp:(id)sender; -(IBAction)curlDown:(id)sender; -(IBAction)dissolve:(id)sender; -(IBAction)noTransition:(id)sender; @end
在 ViewController 类中声明两个视图的实例。ViewController.h文件代码如下:
修改 ViewController.m
我们将添加自定义方法setUpView来初始化视图。
我们还将创建了另一种方法doTransitionWithType: 实现view1切换到view2,反之亦然。
后我们将执行之前创建的操作的方法即调用 doTransitionWithType: 方法与切换类型。ViewController.m代码如下:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self setUpView]; // Do any additional setup after loading the view, typically from a nib. } -(void)setUpView{ view1 = [[UIView alloc]initWithFrame:self.view.frame]; view1.backgroundColor = [UIColor lightTextColor]; view2 = [[UIView alloc]initWithFrame:self.view.frame]; view2.backgroundColor = [UIColor orangeColor]; [self.view addSubview:view1]; [self.view sendSubviewToBack:view1]; } -(void)doTransitionWithType:(UIViewAnimationTransition)animationTransitionType{ if ([[self.view subviews] containsObject:view2 ]) { [UIView transitionFromView:view2 toView:view1 duration:2 options:animationTransitionType completion:^(BOOL finished){ [view2 removeFromSuperview]; }]; [self.view addSubview:view1]; [self.view sendSubviewToBack:view1]; } else{ [UIView transitionFromView:view1 toView:view2 duration:2 options:animationTransitionType completion:^(BOOL finished){ [view1 removeFromSuperview]; }]; [self.view addSubview:view2]; [self.view sendSubviewToBack:view2]; } } -(IBAction)flipFromLeft:(id)sender { [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromLeft]; } -(IBAction)flipFromRight:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromRight]; } -(IBAction)flipFromTop:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromTop]; } -(IBAction)flipFromBottom:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromBottom]; } -(IBAction)curlUp:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionCurlUp]; } -(IBAction)curlDown:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionCurlDown]; } -(IBAction)dissolve:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionCrossDissolve]; } -(IBAction)noTransition:(id)sender{ [self doTransitionWithType:UIViewAnimationOptionTransitionNone]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
输出
现在当我们运行该应用程序我们会看到下面的输出
您可以选择不同的按钮,看切换是如何工作。选择蜷缩切换将效果如下所示
点我分享笔记