How to expose existing property on Obj-C class using an extension protocol in Swift

前端 未结 1 660
终归单人心
终归单人心 2020-12-07 01:06

In Swift 1.1 we were able to have code like below compile and work where we exposed existing Objective-C properties through a protocol added by an extension. We also had a

相关标签:
1条回答
  • 2020-12-07 01:49

    The compiler error message

    note: Objective-C method 'isEnabled' provided by getter for 'enabled' does not match the requirement's selector ('enabled')
    

    gives a hint about the problem. The enabled property of UIButton is inherited from UIControl and in Objective-C declared as

    @property(nonatomic, getter=isEnabled) BOOL enabled
    

    Therefore the protocol method has to be

    @objc protocol Enableable: class {
        var enabled: Bool { @objc(isEnabled) get set }
    }
    

    and the implementation (similarly as in Swift 1.2 error on Objective-C protocol using getter):

    extension UIImageView: Enableable {
        var enabled: Bool {
            @objc(isEnabled) get {
                return alpha > DisabledAlpha
            }
            set(enabled) {
                alpha = enabled ? EnabledAlpha : DisabledAlpha
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题