常見失敗原因
- 當前 ViewController 不在 Navigation Controller 堆疊中:直接
present 或從 Storyboard 進入的 VC 沒有 navigationController 屬性(為 nil)
- 目標 VC 非 UIViewController 子類:如繼承
UITableViewController 需確認正確 import
解決方案
情況一:根視圖控制器需嵌入 Navigation Controller
// AppDelegate 或 SceneDelegate
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:mainVC];
self.window.rootViewController = nav;
情況二:Storyboard 中勾選 "Is Initial View Controller" 並 Editor > Embed In > Navigation Controller
情況三:程式碼中動態嵌入
// 在需要 push 的 VC 內部
if (!self.navigationController) {
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self];
// 視情況 present 或設為 window.rootViewController
}
正確 Push 代碼
- (IBAction)stack:(id)sender {
Page1 *nextVC = [[Page1 alloc] init]; // 或 initWithNibName:bundle:
[self.navigationController pushViewController:nextVC animated:YES];
}
檢查清單
self.navigationController != nil
- 目標 VC 正確初始化(有 nib 則用
initWithNibName:bundle:)
- 未在
push 後立即 pop 或 dismiss