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

iOS Storyboard 多頁面跳轉:手動建立 ViewController 類別並關聯場景

     編輯:程式設計綜合問答

場景

Single View App 專案,Storyboard 已有首頁(自動綁定 ViewController),新增第二個場景需自行建立對應類別並綁定。

步驟 1:新建 Cocoa Touch Class

  1. Xcode 選單 File → New → File…
  2. 選擇 iOS → Source → Cocoa Touch Class
  3. Class 命名:SecondViewController,Subclass of: UIViewController,語言 Swift/Objective-C。
  4. 勾選 Also create XIB file → 取消勾選(我們用 Storyboard)。

步驟 2:Storyboard 關聯場景與類別

  1. 開啟 Main.storyboard。
  2. 點選第二個場景的 View Controller 圖示(場景頂部列左側黃色圖示)。
  3. 開啟 Identity Inspector(右側面板第 3 個圖示,報紙圖標)。
  4. Custom Class → Class 輸入 SecondViewController,按 Enter 確認模組名稱自動填入。

步驟 3:建立 Segue 跳轉(零代碼)

  1. 按住 Control 從首頁按鈕(或任意控制項)拖曳至第二個場景。
  2. 選擇 Show (Push) 或 Present Modally。
  3. 點選生成的 Segue 線(連接兩場景的箭頭),在 Attributes Inspector 設定 Identifier:goToSecond。

步驟 4:程式碼觸發跳轉(可選)

// 首頁 ViewController.swift
@IBAction func loginTapped(_ sender: UIButton) {
    // 若已在 Storyboard 連線 Segue,直接觸發
    performSegue(withIdentifier: "goToSecond", sender: self)
}

// 傳遞資料
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToSecond",
       let dest = segue.destination as? SecondViewController {
        dest.receivedToken = "abc123"
        dest.onComplete = { [weak self] result in
            // 返回資料處理
        }
    }
}

步驟 5:第二頁接收與返回

// SecondViewController.swift
var receivedToken: String?
var onComplete: ((String) -> Void)?

@IBAction func doneTapped(_ sender: UIButton) {
    onComplete?("result from second")
    // 視 Segue 類型決定返回方式
    navigationController?.popViewController(animated: true) // Push
    // 或
    dismiss(animated: true) // Modal
}

常見問題排查

  • ❌ Class 找不到 / 灰色不可編輯 → 確認 Target Membership 勾選專案 Target;清理建置資料夾 Shift+Cmd+K。
  • ❌ performSegue 崩潰 → Identifier 拼寫錯誤,或 Segue 類型與 Navigation 堆疊不符(Modal 不能 Push)。
  • ❌ Outlet 連不上 → 確認檔案擁有者 正確,且屬性宣告 @IBOutlet weak var label: UILabel!。

進階: 大型專案建議改用 Programmatic UI + Coordinator Pattern 或 SwiftUI,減少 Storyboard 合併衝突與耦合。

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