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

iOS 登入成功後如何跳轉到目標頁面?導航控制器實戰

     編輯:程式設計綜合問答

場景

使用者點擊「我的收藏」按鈕 → 未登入 → 彈出登入頁 → 登入成功 → 自動導向「我的收藏」頁。

標準做法:UINavigationController push

// 登入成功的回調中
- (void)loginSuccess {
    // 1. 取得導航控制器
    UINavigationController *nav = self.navigationController;
    // 2. 初始化目標頁面
    MyFavoritesViewController *favVC = [[MyFavoritesViewController alloc] init];
    // 3. 推入堆疊(自帶動畫與返回鍵)
    [nav pushViewController:favVC animated:YES];
}

進階模式

1. 解耦:傳遞目標 VC Class / Storyboard ID

// 登入頁面屬性
@property (nonatomic, strong) Class targetVCClass;
@property (nonatomic, copy) NSString *targetStoryboardID;

// 登入成功
- (void)loginSuccess {
    UIViewController *targetVC;
    if (self.targetVCClass) {
        targetVC = [[self.targetVCClass alloc] init];
    } else if (self.targetStoryboardID) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        targetVC = [sb instantiateViewControllerWithIdentifier:self.targetStoryboardID];
    }
    [self.navigationController pushViewController:targetVC animated:YES];
}

// 呼叫端
LoginViewController *loginVC = ...;
loginVC.targetVCClass = [MyFavoritesViewController class];
// 或
loginVC.targetStoryboardID = @"MyFavoritesVC";

2. 非導航架構:present / 根視圖切換

// 無 UINavigationController 時
[self presentViewController:favVC animated:YES completion:nil];

// 或切換 window.rootViewController(適用於登入後整個 App 狀態變更)
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
app.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:favVC];

3. 保持登入狀態:單例 / Keychain / UserDefaults

登入成功後儲存 Token,後續啟動時在 AppDelegate 判斷自動進入主頁。

最佳實務清單

  • ✅ 使用 pushViewController 保持導航堆疊一致性。
  • ✅ 目標頁面解耦(Class/Storyboard ID),登入頁可複用。
  • ✅ 登入狀態持久化,冷啟動自動導向。
  • ✅ 失敗/取消路徑處理(dismiss/pop 回原頁)。

核心一句:**登入成功 → 取得 navigationController → push 目標 VC**,簡單可靠。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved