我在导航 Controller 中嵌入了两个 ViewController(ViewController 是第一个;SecondViewController 是第二个)。
在ViewController上,viewDidLoad中有一个NotificationCenter观察者。
在 SecondViewController 上,我有一个按钮,该按钮应该向 ViewController 发布通知,当它再次出现时将触发 UIAlertController。
View Controller :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addObservers()
}
func addObservers(){
NotificationCenter.default.addObserver(self, selector: #selector(alertThankYou), name: Notification.Name(rawValue: Constants.handleThankYouNotif), object: nil)
}
func removeObservers(){
NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: Constants.handleThankYouNotif), object: nil)
}
@objc func alertThankYou(notification: Notification) {
self.view.backgroundColor = .red
let alertController = UIAlertController(title: "THANK YOU", message: "lorem ipsum dolor sit amet.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Done", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in
print("done pressed")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
deinit {
removeObservers()
}
}
第二个 View Controller :
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// Press this first to post the Notification!
@IBAction func TRIGGERPOSTPRESSED(_ sender: UIButton) {
NotificationCenter.default.post(name: Notification.Name(Constants.handleThankYouNotif), object: nil)
}
// Then press this to return back to ViewController to HOPEFULLY see an Alert.
@IBAction func close(_ sender: Any) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.window?.rootViewController?.dismiss(animated: true, completion: nil)
(appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: false)
}
}
}
问题:
在 SecondViewController
上,当按下 TRIGGERPOSTPRESSED
时,我在控制台中收到此警告:
Warning: Attempt to present UIAlertController on ViewController whose view is not in the window hierarchy!
应该发生什么:
在 SecondViewController
上,当按下 TRIGGERPOSTPRESSED
时,我不应该收到任何错误。然后,当按下close
并且应用程序返回到ViewController
时,我应该收到警报!
如何使用通知中心实现此目的?
最佳答案
我认为你不应该使用NotificationCenter,在这种情况下,你应该使用委托(delegate)协议(protocol)模式 正如上一个关于 Notification Center vs. Delegation in iOS SDK 的问题当然,这不是问题生成者,但当您只需要两个类进行通信时,使用委派是正确的做法。
关于ios - 使用NotificationCenter在不同 View 上触发UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54542498/