英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论