类型“ NSNotification.Name”没有成员“ keyboardDidShowNotification”

时间:2018-09-13 15:08:54

标签: ios keyboard-events nsnotificationcenter swift4.2

我在Swift 4.2中遇到此错误

  

类型“ NSNotification.Name”没有成员“ keyboardDidShowNotification”

这是我的代码:

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(notification:)), name: NSNotification.Name.keyboardDidShowNotification, object: nil)

以下一项在Swift 4上运行正常,但在Swift 4.2上运行不正常

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)

enter image description here

Apple文档参考号:NSNotification.Name.keyboardDidShowNotification

5 个答案:

答案 0 :(得分:48)

我相信您现在就这样使用它。

NotificationCenter.default.addObserver(
    self, 
    selector: #selector(self.keyboardDidShow(notification:)), 
    name: UIResponder.keyboardDidShowNotification, object: nil) 
//You can substitute UIResponder with any of it's subclass

它在UIResponder doc中作为 Type属性列出。

答案 1 :(得分:5)

快速进行4,2

gca

答案 2 :(得分:2)

除了使用UIResponder.keyboardWillHideNotification之外,我只使用了NSNotification.Name.。这在 SWIFT 5

中有效
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHideNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

答案 3 :(得分:1)

此答案中添加了一些小细节:

func setupViews(){
            // Keyboard notification observers
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) 
    }


    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            // Do something
        }
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        // Do something
    }

答案 4 :(得分:-3)

@Krunal.... 删除 'NSNotification.Name' 它将起作用