首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UINavigationController pushViewController:確保當前 VC 在導航堆疊中

     編輯:程式設計綜合問答

常見失敗原因

  1. 當前 ViewController 不在 Navigation Controller 堆疊中:直接 present 或從 Storyboard 進入的 VC 沒有 navigationController 屬性(為 nil)
  2. 目標 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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved