Error with notification names while converting code to Swift 4.2

最后都变了- 提交于 2019-11-28 07:54:53

问题


The code below was working fine before Swift 4.2:

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

When I click the 'Fix' option, it becomes:

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

But it is still marked an error. Here is the explanation:

Type 'NSNotification.Name' has no member 'UIResponder'

And then I tried to delete 'UIResponder':

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.

...but I don't know how should I complete it.


回答1:


The correct form is:

UIResponder.keyboardWillShowNotification

...so, your code becomes:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification)

This is a known issue with Xcode 10. Automatic Fix-it is not working correctly for Swift 4.2 when it comes to correcting notification names.

In Swift 4.2, lots of Notification.Name instances became instance variables in other classes. For example, keyboardWillShowNotification is now an instance variable of UIResponder.




回答2:


For someone else out there, I was building (what I thought was) a UI-Independent class and did not import UIKit.

Nothing worked until I added at the top of my file, this:

#import UIKit

It appears some notifications (those in UIApplication, UIResponder etc..) may have been refactored into UIKIt.



来源:https://stackoverflow.com/questions/52466147/error-with-notification-names-while-converting-code-to-swift-4-2

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