属性 "isEnabled" 的 UIBarButtonItem 是 class 扩展中无法识别的选择器
Property "isEnabled" of UIBarButtonItem is an unrecognized selector in an extension of the class
在 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
我的代码有什么问题?
不应使用扩展来覆盖任何现有功能。扩展只能用于添加新功能。
对于 Swift 书中的扩展章节:
“Extensions can add new functionality to a type, but they cannot override existing functionality.”
因此,如果您希望覆盖现有功能,正确的解决方案是继承 UIBarButtonItem
。然后在任何需要的地方使用子类。
在 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
我的代码有什么问题?
不应使用扩展来覆盖任何现有功能。扩展只能用于添加新功能。
对于 Swift 书中的扩展章节:
“Extensions can add new functionality to a type, but they cannot override existing functionality.”
因此,如果您希望覆盖现有功能,正确的解决方案是继承 UIBarButtonItem
。然后在任何需要的地方使用子类。