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