NSNotificationCenter能否在Swift中跨目标发布通知?

huangapple go评论98阅读模式
英文:

Can NotificationCenter post cross targets in Swift?

问题

我尝试从键盘类向主应用程序发布通知,并在自定义键盘处于打开状态时更新UI或暂停某些功能。

在键盘的viewDidLoad中:

NotificationCenter.default.post(Notification(name: Notification.Name(Global.KeyboardNotification)))

应用程序的RootViewController:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardStatusChange(_:)), name: Notification.Name.init(rawValue: Global.KeyboardNotification), object: nil)

实现:

@objc func keyboardStatusChange(_ notification: Notification) {
    NSLog(TAG, "\(#function)")
}

然而,这个函数从未被调用过,但这些本机API却能正常工作:

UIApplication.keyboardDidShowNotification
UIApplication.keyboardWillHideNotification

我不确定为什么通知没有被调用,但本机通知可以,可能是苹果不允许跨越通知或其他我可能忽略的事情?

英文:

I'm trying to post a notification from keyboard class to main app, and update UI or suspend some feature wile the custom keyboard is on.

In keyboard's viewDidLoad:

NotificationCenter.default.post(Notification(name: Notification.Name(Global.KeyboardNotification)))

RootViewController of the app

NotificationCenter.default.addObserver(self, selector: #selector(keyboardStatusChange(_:)), name: Notification.Name.init(rawValue: Global.KeyboardNotification), object: nil)

The implementation:

@objc func keyboardStatusChange(_ notification: Notification) {NSLog(TAG, "\(#function)")}

The function never been called, however these native api are working well:

UIApplication.keyboardDidShowNotification
UIApplication.keyboardWillHideNotification

I'm not sure why the notification not been called, but native can, is Apple doesn't allow notification cross or other things that I may missed?

答案1

得分: 1

尝试使用这段代码,希望能解决你的问题。

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
英文:

try to use this code, hopefully it will solve your problem

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)

huangapple
  • 本文由 发表于 2023年8月10日 15:53:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定