在 Storyboard 上拉線可以完成固定流程的跳轉,但一旦需要「依條件決定去哪一頁」,就必須回到程式碼。以下兩個片段是最常用的寫法。
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"yourStoryboardName" bundle:nil]; UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"yourStoryboardId"]; [self.navigationController pushViewController:viewController animated:YES];
這樣做的好處是:你可以在此之前加上任何邏輯判斷——檢查登入狀態、依使用者權限切換不同頁面、或根據伺服器回傳的結果決定下一步,這些都是 Storyboard 上的實體連線做不到的事。
使用這個方法前,別忘了在 Storyboard 的 Identity Inspector(⌥⌘3)中為該 scene 設定 Storyboard ID,否則會在執行期拿到 nil 並崩潰。
UIViewController *viewController = [storyboard instantiateInitialViewController];
這會回傳該 storyboard 中被標記為「Is Initial View Controller」的那一頁。常見用途是登出後跳回登入頁:
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *loginVC = [sb instantiateInitialViewController]; [self presentViewController:loginVC animated:YES completion:nil];
instantiateViewControllerWithIdentifier: 每次都會「新建立」一個實例,不會重用堆疊中已存在的同一個物件。若需要回到既有頁面,應改用 pop/dismiss。instantiateInitialViewController 時,該 storyboard 必須確實有設定初始控制器,否則回傳 nil。let sb = UIStoryboard(name: "Main", bundle: nil) let vc = sb.instantiateViewController(withIdentifier: "yourStoryboardId") navigationController?.pushViewController(vc, animated: true)