您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多 Storyboard 架構:跨檔案跳轉的完整做法

編輯:iOS 開發綜合

Storyboard 可以視為畫面(scene)與轉場(segue)的集合,而一個 iOS 專案並不限制只能有一個。當團隊人數變多、功能模組變多時,把相關畫面歸到同一個 Storyboard 裡分檔管理,比全部塞進 Main.storyboard 好維護得多——後者一旦超過幾十個 scene,光是在 Xcode 裡滾動就夠痛苦,多人同時修改也容易衝突。

步驟一:準備兩個 Storyboard

在專案中新增第二個 Storyboard 檔案(File → New → User Interface → Storyboard),命名為 Storyboard2.storyboard。

步驟二:佈置第一個 Storyboard

拉出一個 Navigation Controller 作為起點,在它的 root view controller 上放一顆 Button,稍後要在這顆按鈕的 action 裡寫跳轉程式。

步驟三:佈置第二個 Storyboard

同樣拉一個 Navigation Controller 進來。在它的 root 畫面上放一個 Label,文字改成「Storyboard2」,只是用來確認畫面確實被導到第二個檔案去。

這裡有個關鍵設定:選取該 view controller,在 Identity Inspector 中把 Storyboard ID 填為 test2。這個值稍後會被程式碼引用。

步驟四:撰寫跨 Storyboard 跳轉程式碼

在第一個 Storyboard 那顆按鈕的 Touch Up Inside 事件中寫入:

UIStoryboard *secondStoryboard = [UIStoryboard storyboardWithName:@"Storyboard2"
                                                          bundle:nil];

UIViewController *test2VC = [secondStoryboard instantiateViewControllerWithIdentifier:@"test2"];

[self.navigationController pushViewController:test2VC animated:YES];

三行程式各負責一件事:

  1. 以 storyboardWithName:bundle: 取得第二個 Storyboard 的物件。名稱就是檔名去掉副檔名,bundle 傳 nil 表示在主要 bundle 中尋找。
  2. 用 instantiateViewControllerWithIdentifier: 從該 Storyboard 中依 Storyboard ID 產生 view controller 實例。這裡的 test2 必須與步驟三設定的值完全一致,寫錯會在執行期丟出例外。
  3. 用目前導覽控制器的 pushViewController: 推入堆疊,完成畫面切換。

幾個實務考量

  • 跨 Storyboard 跳轉無法用 segue 線條連接,只能靠程式碼,這也意味著跳轉邏輯會散落在各 controller 中。若跳轉關係變複雜,建議集中到一個負責路由的物件裡管理。
  • 如果目標 view controller 需要接收參數,在 push 之前直接設定屬性即可,這點與同 Storyboard 內的 prepareForSegue:sender: 做法略有不同。
  • 另一個常見作法是設定初始 Storyboard:在專案的 target 設定裡有 Main Interface 一欄,程式碼中則可用 [UIStoryboard storyboardWithName:... instantiateInitialViewController] 動態決定啟動畫面,實作快速登入跳過引導頁這類需求時很順手。
  • Storyboard 拆檔的界線建議依「功能模組」而非「畫面數量平均分配」來切,例如登入註冊一檔、下單流程一檔、設定一檔。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved