您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

用程式碼在 Storyboard 畫面之間跳轉與取得初始控制器

編輯:iOS 技巧大全

在 Storyboard 上拉線可以完成固定流程的跳轉,但一旦需要「依條件決定去哪一頁」,就必須回到程式碼。以下兩個片段是最常用的寫法。

一、指定 storyboard 與 Storyboard ID 建立控制器

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 並崩潰。

二、取得 Storyboard 的初始控制器

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。
  • 若同一個 scene 需要在多處以不同 identifier 呈現,可以在同一個 storyboard 中放多份並各給不同 ID。
  • 使用 instantiateInitialViewController 時,該 storyboard 必須確實有設定初始控制器,否則回傳 nil。
  • Swift 對應寫法:
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "yourStoryboardId")
navigationController?.pushViewController(vc, animated: true)
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved