在開發 iOS App 時,切換 UIViewController 是最基礎也最常遇到的任務。這篇筆記整理我在切換 View 時常用到的函數:有 NavigationController 時怎麼切入與返回、沒有 NavigationController 時怎麼做,以及如何取得子或父 ViewController。
切換 UIViewController 有哪兩種方式?
切換 UIViewController 主要分成兩種情境:有 NavigationController 時,以及沒有 NavigationController 時。
1. 有 NavigationController 時怎麼切換 View?
方法一:從右側進入
```objc
SecondViewController* svc=[[SecondViewController alloc]init];
[self.navigationController pushViewController:svc animated:YES];
```
返回到上一頁
```objc
[self.navigationController popViewControllerAnimated:YES];
```
方法二:從下面切入
```objc
SecondViewController* svc=[[SecondViewController alloc]init];
[self.navigationController presentModalViewController:svc animated:YES];
```
返回到上一個 UIViewController
```objc
[self.navigationController dismissModalViewControllerAnimated:YES];
```
2. 沒有 NavigationController 的切換方法
```objc
SecondViewController* svc=[[SecondViewController alloc]init];
[self presentModalViewController:svc animated:YES];
```
返回到上一個 UIViewController
```objc
[self dismissModalViewControllerAnimated:YES];
```
怎麼取得子 ViewController 或父 ViewController?
假設 View A 是來源的 ViewController,而 View B 是目標 ViewController。
1. 取得子 viewController
```objc
((B *)self.presentedViewController).屬性名
```
2. 取得父 viewController
```objc
((A *)self.presentingViewController).屬性名
```
其中括號和類名是一種強制轉型(cast)的用法,把取得的 ViewController 轉成我們知道的類別,就可以直接存取它的屬性。
延伸閱讀
- iOS 切換 ViewController 會用到的函數整理:同樣聚焦 Objective-C、iOS,可接著比較不同情境的做法。
- iOS UIView 操作與 Core Graphics 繪圖入門:同樣聚焦 UIView、iOS,可接著比較不同情境的做法。
- iOS 6 以上如何控制畫面支援的旋轉方向:同樣聚焦 iOS、Objective-C,可接著比較不同情境的做法。
常見問題
pushViewController 和 presentModalViewController 有什麼差別?
pushViewController 是把新的 ViewController 推進 Navigation Stack,畫面從右側滑入,適合有層級關係的頁面導覽。presentModalViewController 則是以 Modal 方式從下面切入,適合暫時性、獨立的任務畫面。
沒有 NavigationController 時要怎麼切換 View?
直接在目前的 ViewController 上呼叫 presentModalViewController:animated: 切入新頁面,返回時呼叫 dismissModalViewControllerAnimated: 即可,不需要透過 navigationController。
presentModalViewController 之後怎麼取得對方的資料?
用 self.presentedViewController 取得子 ViewController、self.presentingViewController 取得父 ViewController,再透過強制轉型(例如 `((B *)self.presentedViewController)`)存取該類別的屬性。
切換 View 之後要怎麼返回上一頁?
有 NavigationController 時用 popViewControllerAnimated: 或 dismissModalViewControllerAnimated:;Modal 方式切入的則用 dismissModalViewControllerAnimated: 返回上一個 UIViewController。
最後更新
2026-08-28(原文發布於 2013-08-18,本文保留原始筆記內容並補上 GEO 結構。)
關於作者 {#author}
Claire Chang | 企業 AI 導入與流程轉型顧問。專注於 AI Agent 架構設計、ERP 系統整合與企業 AI 治理。
首次發布:2013-08-18
