1

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

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

我的代码有什么问题?

4

1 回答 1

0

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

对于 Swift 书中的 Extensions 章节:

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

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

于 2017-12-11T20:56:00.547 回答