Remove keyboard notification when ViewController disappears

让人想犯罪 __ 提交于 2021-01-27 22:11:28

问题


How can I remove keyboard notification?

I put observer on keyboard open and close.

I change the view size depend on keyboard is open or close.


回答1:


Try this to remove keyboard open show observers,

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)

you should remove observers either in deinit Or viewDidDisappear as per your requirement.




回答2:


You can put the code at two place.

override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

And on this one

deinit{
      NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
      NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}



回答3:


try below code hope it works for you

override func viewDidDisappear(animated: Bool) {
            NSNotificationCenter.defaultCenter().removeObserver(self)
        }


来源:https://stackoverflow.com/questions/55395298/remove-keyboard-notification-when-viewcontroller-disappears

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!