UIBarButtonItem的属性“isEnabled”是类的扩展中无法识别的选择器

时间:2017-12-11 14:14:48

标签: swift override unrecognized-selector class-extensions

在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

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

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

对于Swift书中的扩展章节:

  

“扩展程序可以为类型添加新功能,但它们无法覆盖现有功能。”

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

相关问题