【问题标题】:Property "isEnabled" of UIBarButtonItem is an unrecognized selector in an extension of the classUIBarButtonItem 的属性“isEnabled”是类扩展中无法识别的选择器
【发布时间】:2017-12-11 14:14:47
【问题描述】:

在 Swift 4 中,我想使用 UIBarButtonItem扩展 来实例化一个特殊的 UIBarButtonItem 对象。
这是我的代码(仅是基本语句):

import Foundation

extension UIBarButtonItem {

    convenience init(staticImageName: String) {
        let staticView = UIImageView.init(image: UIImage(named: staticImageName))
        self.init(customView: staticView)
//      further code…
    }

    override open var isEnabled: Bool { 
        didSet { 
            print("didSet called") // Should be replaced by other code…
        } 
    } 

} // extension UIBarButtonItem

这个扩展构建没有问题。

但是,当我运行应用程序时,我在语句中收到运行时错误
self.init(customView: staticView)
日志说:

-[UIBarButtonItem isEnabled]: unrecognized selector sent to instance 0x7fe20c505180

我的代码有什么问题?

【问题讨论】:

  • isEnabled 不是 UIBarButtonItem 的属性。
  • @Jacky 但它是它的超类UIBarItem的属性
  • 请参考这个,可能对你有帮助:stackoverflow.com/questions/3784112/…
  • 扩展用于添加新功能。不得使用扩展来覆盖任何内容。如果要覆盖,请创建一个子类。来自 Swift 书籍:““扩展可以为类型添加新功能,但不能覆盖现有功能。”
  • 有类似的问题。从 Xcode 9 / iOS SDK 11 开始,UIBarButtonItem 的 isEnabled 似乎无法按预期工作。我将 UIBarButtonItem 更改为使用 UIButton 作为自定义视图,以便能够使用 UIButton 的 isEnabled

标签: swift overriding unrecognized-selector class-extensions


【解决方案1】:

不应使用扩展来覆盖任何现有功能。扩展只应该用于添加新功能。

关于 Swift 书中的扩展章节:

“扩展可以为类型添加新功能,但不能覆盖现有功能。”

因此,如果您希望覆盖现有功能,正确的解决方案是继承 UIBarButtonItem。然后在需要的地方使用子类。

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多