【问题标题】:Error with notification names while converting code to Swift 4.2将代码转换为 Swift 4.2 时出现通知名称错误
【发布时间】:2019-02-27 04:29:18
【问题描述】:

以下代码在 Swift 4.2 之前运行良好:

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

当我点击“修复”选项时,它变成:

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

但它仍然被标记为错误。解释如下:

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

然后我尝试删除“UIResponder”:

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

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

【问题讨论】:

    标签: nsnotifications xcode10 swift4.2


    【解决方案1】:

    正确的形式是:

    UIResponder.keyboardWillShowNotification
    

    ...所以,您的代码变为:

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

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

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

    【讨论】:

    • 我不知道这一点:'自动修复 - 在更正通知名称时,它在 Swift 4.2 中无法正常工作。' (非常感谢)
    • 这段代码不走运......在 UIWindow 类中实现了这段代码“NotificationCenter.default.addObserver(self, selector: #selector(self.bringWindow(toTop:)), name: UIWindow. didBecomeVisibleNotification,对象:nil)"
    • 获取Cannot invoke 'addObserver' with an argument list of type '(RegistrationViewController, selector: Selector, name: NSNotification.Name)'
    • @SazzadHissainKhan 抱歉,Madhu_Nani 是对的 - object: nil 不见了。我已经编辑了我的帖子
    【解决方案2】:

    对于那里的其他人,我正在构建(我认为是)一个独立于 UI 的类并且没有导入 UIKit。

    在我添加到文件顶部之前,没有任何效果:

    import UIKit
    

    似乎某些通知(在 UIApplication、UIResponder 等中的通知)可能已被重构为 UIKIt。

    【讨论】:

      【解决方案3】:

      选中的answer不完整,会产生编译错误,

      无法使用类型参数列表调用“addObserver” '(RegistrationViewController,选择器:选择器,名称: NSNotification.Name)'

      这是工作格式,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-14
        • 1970-01-01
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多