【发布时间】: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