将代码转换为Swift 4.2时,通知名称出错

man*_*era 6 nsnotifications xcode10 swift4.2

在Swift 4.2之前,下面的代码运行正常:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
Run Code Online (Sandbox Code Playgroud)

当我单击"修复"选项时,它变为:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

但它仍然标记错误.这是解释:

Type 'NSNotification.Name' has no member 'UIResponder'
Run Code Online (Sandbox Code Playgroud)

然后我试图删除'UIResponder':

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.
Run Code Online (Sandbox Code Playgroud)

......但我不知道该如何完成它.

Tam*_*gel 26

正确的形式是:

UIResponder.keyboardWillShowNotification
Run Code Online (Sandbox Code Playgroud)

...所以,你的代码变成:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification)
Run Code Online (Sandbox Code Playgroud)

这是Xcode 10的一个已知问题.自动修复 - 在更正通知名称时,它无法正常使用Swift 4.2.

在Swift 4.2中,许多Notification.Name实例成为其他类中的实例变量.例如,keyboardWillShowNotification现在是一个实例变量UIResponder.

  • 这段代码没有运气....在 UIWindow 类“NotificationCenter.default.addObserver(self, selector: #selector(self.bringWindow(toTop:)), name: UIWindow.didBecomeVisibleNotification, object: nil)”中实现了这段代码 (2认同)