iOS 教程
視圖切換通過一系列動(dòng)畫效果實(shí)現(xiàn),包括折疊切換、爆炸切換、卡片式切換等等。
在 xib 中創(chuàng)建按鈕的操作
#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 類中聲明兩個(gè)視圖的實(shí)例。ViewController.h文件代碼如下:
我們將添加自定義方法setUpView來初始化視圖。
我們還將創(chuàng)建了另一種方法doTransitionWithType: 實(shí)現(xiàn)view1切換到view2,反之亦然。
后我們將執(zhí)行之前創(chuàng)建的操作的方法即調(diào)用 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
現(xiàn)在當(dāng)我們運(yùn)行該應(yīng)用程序我們會(huì)看到下面的輸出
您可以選擇不同的按鈕,看切換是如何工作。選擇蜷縮切換將效果如下所示