折騰了一整天,本文總結一下ios7.0頁面跳轉有關的內容
storyboard的潛規則
我接觸ios很晚,環境已經是xcode5+ios7,所以對以前的IOS開發模式并不了解。在網上查閱了很多資料,發現以前的代碼,很多都需要自己coding來創建ViewController,比如:
- WTwoViewController *controller = [[WTwoViewController alloc]initWithNibName:@"WTwoViewController" bundle:nil];
- [self PResentViewController:controller animated:YES completion:nil];
但是用storyboard來管理view controller的話,storyboard會自動處理view controller的初始化動作,所以就不再需要自己coding來創建view controller的實例。在另外一篇博客里看到這句話:
“用過xib的人我相信很多人都會經常用到-presentModalViewController:animated:以及-pushViewController:animated:這兩個方法。這種代碼在storyboard里將成為歷史;取而代之的是Segue”
基于控件的跳轉
用storyboard做開發,經常需要拉線,本文不介紹,請看這篇官方文檔:
start developing iOS app today
這種拉線,是從button拉到view controller:

這種方式只要點擊了這個button,就會自動跳轉,不需要寫任何代碼
直接從controller到controller
這種拉線是直接從View Controller到View Controller:
這種方式已經預先創建了segue,但是還需要手工編碼,首先需要給segue設置一個identity
然后寫代碼來跳轉:
- // 跳轉到bootstrap
- - (void) jumpToBootstrap{
- [self performSegueWithIdentifier:@"fromWelcomeToBootstrap" sender:self];
- }
這段代碼必須寫在-viewDidAppear里,不能寫在-viewDidLoad里,否則會報一個錯誤:whose view is not in window hierarchy!
頁面之間傳值
以前用-presentModalViewController:animated:方法來跳轉的時候,一般需要通過delegate等方式來傳值,現在一律用segue API就能搞定
在segue發生之前,先會調用當前View Controller的-prepareForSegue:sender:方法,可以在里面做一些處理,比如:
- BootstrapViewController* targetController = [segue destinationViewController];// 拿到目標view controller,然后要怎么樣都可以了
不過這里要注意的是,似乎不能在prepareForSegue方法里設置destination view controller的view,因為這個時候view還沒有被storyboard實例化。不過可以先傳參,后面再設置
另外網上看到很多帖子,都說從B回到A的時候如果也需要傳值,可以把A設置成B的delegate:
- BViewController.delegate = self;
這里我不是很理解,當從B回到A的時候,也設置一個segue似乎就行了
unwind segue
unwind segue比較特殊,是在目標View Controller里先設置一個action,然后在source View Controller里拖線到exit圖標上。這種情況下,除了會調用source的prepareForSegue方法以外,target View Controller的那個action也會被調用。