首页 > 解决方案 > 类型“NSNotification.Name”没有成员“UIResponder”

问题描述

我在使用 Swift 5 时遇到了这个错误

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)

在此处输入图像描述

我也遇到了错误

“名称”不是“通知”的成员类型

public let ImagePickerTrayDidHide: Notification.Name = Notification.Name(rawValue: "ch.laurinbrandner.ImagePickerTrayDidHide")

我该如何解决?

标签: swift5

解决方案


正如我最初猜想的那样,您有以下代码:

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

当您在 Xcode 10.1 中编译它时,您收到以下错误:'keyboardWillShowNotification' has been renamed to 'NSNotification.Name.UIKeyboardWillShow', Replace 'keyboardWillShowNotification' with 'NSNotification.Name.UIKeyboardWillShow''keyboardWillHideNotification' has been renamed to 'NSNotification.Name.UIKeyboardWillHide', Replace 'keyboardWillHideNotification' with 'NSNotification.Name.UIKeyboardWillHide'.

然后你按了两次“修复”,得到了你已经添加到问题中的错误代码。您应该使用以下内容:

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

推荐阅读