我在 Storyboard中创建了 UIViewController (A),并使用 UINavController 添加了容器。
我嵌入的 UINavController 的根是带有按钮的 UIViewController (B)。
如果我点击按钮,NavController 会显示新的 UIViewController (C)。
所以我有 UINavController -> B -> C。A Controller 如何检测其包含的 NavController 内的 B -> C 转换?
有多种方法可以做到这一点,但最简单的解决方案可能是使用通知中心。每当通知发布时,您都会监听通知,为其指定一个唯一的名称,例如 ViewA 或 ViewB 通知,然后监听具有该名称的通知。检查下面的示例:-
import UIKit
struct NotificationNames {
static let bViewController
static let cViewController
}
class AViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Listen for notification of from BViewcontroller
NotificationCenter.default.addObserver(self, selector: #selector(didLoadBViewController), name: Notification.Name(NotificationNames.bViewController), object: nil)
// Listen for notification of from CViewcontroller
NotificationCenter.default.addObserver(self, selector: #selector(didLoadCViewController), name: Notification.Name(NotificationNames.cViewController), object: nil)
}
@objc private func didLoadBViewController() {
print("B ViewController is loaded.")
}
@objc private func didLoadCViewController() {
print("C ViewController is loaded.")
}
// Remove notification listeners to save some memory
deinit {
NotificationCenter.default.removeObserver(self, name: NotificationNames.bViewController, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationNames.cViewController, object: nil)
}
}
class BViewcontroller: UIViewController {
// Post notification that B ViewController loaded.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
NotificationCenter.default.post(name: NotificationNames.bViewController, object: nil)
}
}
class CViewController: UIViewController {
// Post notification that C ViewController loaded.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
NotificationCenter.default.post(name: NotificationNames.cViewController, object: nil)
}
}
Tôi là một lập trình viên xuất sắc, rất giỏi!