Error with notification names while converting code to Swift 4.2

后端 未结 3 646
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 16:07

The code below was working fine before Swift 4.2:

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


        
相关标签:
3条回答
  • 2020-12-20 16:38

    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.

    0 讨论(0)
  • 2020-12-20 16:42

    The correct form is:

    UIResponder.keyboardWillShowNotification
    

    ...so, your code becomes:

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

    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.

    0 讨论(0)
  • 2020-12-20 16:54

    The selected answer is incomplete and produce compilers error,

    Cannot invoke 'addObserver' with an argument list of type '(RegistrationViewController, selector: Selector, name: NSNotification.Name)'

    Here is the working format,

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    
    0 讨论(0)
提交回复
热议问题