一种选择是使用NotificationCenter,让您的按钮发布通知,并让您的子视图控制器监听它们。
例如,在父VC中,在点击按钮时调用的函数中发布通知,如下所示:
@IBAction func buttonTapped(_ sender: UIButton) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil, userInfo: nil)
}
在需要响应按钮点击的子 VC 中,将以下代码放入 viewWillAppear: 以将 VC 设置为该特定通知的侦听器:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(handleButtonTap(_:)), name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil)
}
在同一个视图控制器中,添加上面提到的handleButtonTap:方法。当“ButtonTapped”通知进来时,就会执行这个方法。
@objc func handleButtonTap(_ notification: NSNotification) {
//do something when the notification comes in
}
当不再需要视图控制器时,不要忘记将其作为观察者移除,如下所示:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}