學習view製作及切換的幾種方式
Mac OS X 10.7.2
Xcode4.2
- 詳解
- 在storyboard中建立另一個ViewController並使用Segue切換
在storyboard中再增加一個ViewController。在兩個ViewController中各增加一個按鈕。右擊按鈕,在快顯功能表中拖放“Modal”圈圈到另一個ViewController上放手即可。
- 在xib檔案中建立另一個ViewController並使用代碼手動切換
在工程中添加檔案,選擇建立“UIViewController subclass”,在嚮導中勾選“With XIB for user interface”,取名為“SecondViewController”,完成後得到3個檔案:"SecondViewController.h"、"SecondViewController.m“、"SecondViewController.xib”。
在xib中添加一個按鈕,並為其添加事件處理函數,在函數中增加如下代碼以用於退出當前的view回到首頁:
- (IBAction)exitCurrentView:(id)sender { [self.view removeFromSuperview];}
在首頁的ViewController.h中添加此xib對應的變數,如下所示:
@interface ViewController : UIViewController{ SecondViewController* secondViewController;}
背後的切換按鈕事件函數代碼為:
- (IBAction)switchToSecondView:(id)sender { secondViewController=[[SecondViewController new] initWithNibName:@"SecondViewController" bundle:nil]; [self.view addSubview:secondViewController.view];}
- (IBAction)switchToThirdView:(id)sender { //先建立view thirdView=[[UIView alloc] initWithFrame:self.view.bounds]; thirdView.backgroundColor=[UIColor greenColor]; //為view增加控制項 UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(100, 100, 100, 100); [button setTitle:@"回首頁" forState:UIControlStateNormal]; [button addTarget:self action:@selector(exitThirdView:) forControlEvents:UIControlEventTouchUpInside]; [thirdView addSubview:button]; //將view顯示出來 //加入動畫吧 [UIView beginAnimations:@"flipping view" context:nil]; [UIView setAnimationDuration:1]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:NO]; [self.view addSubview:thirdView]; [UIView commitAnimations];}- (void)exitThirdView:(id)sender{ //也加入動畫效果 [UIView beginAnimations:@"flipping view" context:nil]; [UIView setAnimationDuration:1]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO]; [thirdView removeFromSuperview]; [UIView commitAnimations];}