如何使用Swift中的扩展协议公开Obj-C类上的现有属性 [英] How to expose existing property on Obj-C class using an extension protocol in Swift

查看:122
本文介绍了如何使用Swift中的扩展协议公开Obj-C类上的现有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 1.1中,我们能够使用下面的代码编译和工作,我们通过扩展添加的协议公开现有的Objective-C属性。我们还有一些扩展处理属性的地方。

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 few where the property is handled by the extension.

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

let DisabledAlpha: CGFloat = 0.5
let EnabledAlpha: CGFloat = 1.0

extension UIButton: Enableable {}

extension UIImageView: Enableable {
    var enabled: Bool {
        get {
            return alpha > DisabledAlpha
        }
        set(enabled) {
            alpha = enabled ? EnabledAlpha : DisabledAlpha
        }
    }
}

尝试时使用XCode 6.3和Swift 1.2编译此代码,我们得到以下错误类型'UIButton'不符合协议'Enableable'。 UIImageView扩展似乎编译得很好。

When trying to compile this code using XCode 6.3 and Swift 1.2, we get the following error Type 'UIButton' does not conform to the protocol 'Enableable'. The UIImageView extension seems to compile fine.

有没有办法从Objective-C类型公开这些类型的现有属性,或者我们是否必须实现代理属性一个不同的名字?

Is there any way to expose these sort of existing properties from an Objective-C type or do we have to implement a proxying property with a different name?

推荐答案

编译器错误信息


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

给出了一个关于问题的提示。 UIButton 已启用属性继承自 UIControl 并且Objective-C声明为

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

因此协议方法必须是

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

和实施(类似于使用getter在Objective-C协议上出现Swift 1.2错误):

extension UIImageView: Enableable {
    var enabled: Bool {
        @objc(isEnabled) get {
            return alpha > DisabledAlpha
        }
        set(enabled) {
            alpha = enabled ? EnabledAlpha : DisabledAlpha
        }
    }
}

这篇关于如何使用Swift中的扩展协议公开Obj-C类上的现有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆