如何在 Swift 4.2 中编写键盘通知?

Việ*_* Lê 3 nsnotificationcenter ios swift swift3 swift4.2

我正在尝试将此代码从 Swift 3 更新到 Swift 4.2

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: .UIKeyboardDidShow, object: nil);
Run Code Online (Sandbox Code Playgroud)

到目前为止,我刚刚尝试了编译器给出的自动更正。这导致如下代码:

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: .UIResponder.keyboardDidShowNotification, object: nil);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这并没有让我走多远,导致额外的错误:“没有更多上下文的表达类型是不明确的”
有没有人解决这个问题? 在此处输入图片说明

Dha*_*esh 7

只需替换.UIResponder.keyboardDidShowNotificationUIResponder.keyboardDidShowNotification,它将解决您的问题。

最终代码将是:

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)