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

iOS 開發:三種頁面跳轉方式詳解(代碼 + Storyboard)

     編輯:程式設計綜合問答

場景描述

初學者構建登錄界面,點擊「登錄」按鈕後需跳轉至主應用界面。iOS 提供多種導航跳轉方式,掌握其區別與適用場景至關重要。

方式一:Navigation Controller 推疊

適用於有導航欄的層級式頁面(如設置頁、列表詳情)。

// Swift
let vcB = ViewControllerB()
navigationController?.pushViewController(vcB, animated: true)

// Objective-C
ViewControllerB *vcB = [[ViewControllerB alloc] init];
[self.navigationController pushViewController:vcB animated:YES];
  • 前提:當前 VC 嵌入在 UINavigationController 中。
  • 返回:用戶可點擊導航欄返回鍵或滑動手勢返回。
  • 生命週期:viewWillDisappear → viewDidDisappear (A);viewWillAppear → viewDidAppear (B)。

方式二:Modal 模態彈出

適用於任務型、臨時性、需強制完成的頁面(如登錄、拍照、選擇器)。

// Swift (iOS 13+ 自動適配 presentationStyle)
let vcB = ViewControllerB()
vcB.modalPresentationStyle = .fullScreen // 或 .pageSheet, .formSheet
present(vcB, animated: true, completion: nil)

// Objective-C
ViewControllerB *vcB = [[ViewControllerB alloc] init];
vcB.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:vcB animated:YES completion:nil];
  • 無需 Navigation Controller。
  • 返回:必須在 B 中調用 dismiss(animated:completion:)。
  • iOS 13+ 默認 .pageSheet 可下拉關閉,需設置 .fullScreen 保持全屏。

方式三:Storyboard Segue 視覺化跳轉

適用於靜態流程、原型快速構建、團隊協作。

  1. 在 Storyboard 中按住 Control 從按鈕/Cell 拖拽到目標 VC。
  2. 選擇 Show (Push) 或 Present Modally。
  3. 點擊生成的 Segue,在 Attributes Inspector 設置 Identifier(如 "goMain")。
  4. 代碼觸發:performSegue(withIdentifier: "goMain", sender: self)。

進階:傳值與解耦

// 準備跳轉時傳值 (Segue 方式)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goMain" {
        let dest = segue.destination as! MainViewController
        dest.userToken = self.loginToken
    }
}

// 程式化跳轉傳值
let vcB = ViewControllerB()
vcB.userToken = self.loginToken
navigationController?.pushViewController(vcB, animated: true)

選型建議

場景推薦方式理由
功能模塊逐級深入(列表→詳情→編輯)Push自帶導航欄、返回棧、符合用戶心智模型
登錄、註冊、支付、拍照、選擇器Modal (.fullScreen)強制聚焦、任務完成前不離開、獨立上下文
靜態流程、設計師主導、少量動態邏輯Segue可視化、減少樣板代碼、易於團隊溝通
複雜動態條件、深度鏈接、程式化控制代碼 Push/Present靈活、可測試、支持依賴注入

提示: 現代 iOS 開發推薦「代碼為主,Storyboard 輔助」或純代碼(Programmatic UI),便於版本控制、Code Review 與重構。

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