NavigationController (root: A)
└─ push → B
└─ present → C (modal)
目標:在 C 點選按鈕,**關閉 C 並回到 A**(B 也要移除)。
delegate 協議或 **Closure/Block** 回調,或發送 NotificationCenter 通知。dismiss(animated: true) { /* completion */ } 先關閉自己。dismiss 的 completion 或通知觀察者中,讓 **NavigationController** 執行 popToRootViewController(animated: true)(回到 A)。// CViewController
protocol CDelegate: AnyObject { func cDidRequestReturnToRoot() }
weak var delegate: CDelegate?
@IBAction func backToA(_ sender: UIButton) {
dismiss(animated: true) {
self.delegate?.cDidRequestReturnToRoot()
}
}
// BViewController (或 AViewController) 符合協議並設為 C 的 delegate
func cDidRequestReturnToRoot() {
navigationController?.popToRootViewController(animated: true)
}
// 或用 NotificationCenter (無需 delegate 耦合)
// C: NotificationCenter.default.post(name: .returnToRoot, object: nil)
// A/B: 觀察 .returnToRoot 執行 popToRootViewController
dismiss C,再 pop 到根,動畫順暢且導航棧乾淨。popToRootViewController 會一次彈出所有 push 進來的控制器。