PS.
1. Storyboard 拉出來的 ViewController,常常仍需要新增一個 ViewController class 來搭配
2. ViewController 之間使用 Segue 來進行串接,兩個 ViewController 間可以有多個 Segue 做串接,使用 Identifier 來進行識別
實作:
開啓一個 Storyboard 專案,加入 3 個 ViewController,
為了辨識方便我們將 background 設為不同顏色,
使用 Segue 來串接各個 ViewController,
在 Main View 加入兩個按鈕:Go Directly、Go Random,
按下 Go Directly 可直接通往其中一個指定的 ViewController,
而 Go Random 則會隨機通往其中一個 ViewController。
首先,先實作 "按下 Go Directly" 按鈕後,會直接進入指定 ViewController 這個功能:
在 Go Directly 這個按鈕上按下右鍵,將 Triggered Segues 裡 action 連接到欲進入的 ViewController,
選擇 modal (稍後會提到 modal、push 的差別)
正確連結後面話應該會如下:
執行後,按下 Go Directly 應該就可以進入藍色的 ViewController 了。
另外,點選 segue,在 attributes inspector 中有四個預設效果可選。
接下來,讓我們在 blue ViewController 上建立一個 button 用於返回上一個 main ViewController
首先:
1. 在 main ViewController 中建立一個”返回”用的 method
-(IBAction)backToFirst:(UIStoryboardSegue *) segue {
NSLog(@"back to FirstPage");
}
2. 回到 blue ViewController 在按鈕上點擊右鍵,連接到下方綠色的 Exit 選擇剛建立的方法
3. 完成後按下按鈕,就可以返回 main ViewController 了
注意:
以往我們使用 -(IBAction) 型態的 method 時,後面的參數都是帶 (id)sender,
而在此所使用的參數其型態為 (UIStoryboardSegue *),
如此才能讓按鈕在連結 Exit 時接收到。
接下來我們來實作:
按下 Go Random 按鈕會隨機通往其中一個 ViewController
首先,先建立 main ViewController 跟 Black ViewController、Green Viewcontrller 的關聯
點選 main ViewController 然後按右鍵,將 Triggered Segue 裡的 manual 拖拉至另一個 ViewController 選擇 modal
如此一來關聯就建立了,
接下來,爲各個 Segue 設置其 Identifier
分別設置好 goBlue、goGreen、goBlack 後,就可以開始撰寫 Go Random 這個 button 的 IBAction 了
- (IBAction)goRandomBtn:(id)sender {
NSInteger targetIndex = arc4random() % 3;
switch (targetIndex) {
case 0:
[self performSegueWithIdentifier:@"goBlue" sender:nil];
break;
case 1:
[self performSegueWithIdentifier:@"goGreen" sender:nil];
break;
case 2:
[self performSegueWithIdentifier:@"goBlack" sender:nil];
break;
default:
break;
}
}
寫好後,再將 Go Random 與剛剛寫好的 IBAction 建立起關聯,(如果無法建立代表我們忘了在 .h 檔裡宣告 - (IBAction)goRandomBtn:(id)sender;)
完成!





