在UIView及其子类上使用不同方法的相同属性

时间:2017-06-27 12:20:54

标签: swift uiview swift-protocols

因此要求在所有UIView子类上都有一个属性,如myView.property。对于许多子类而言,会有一些特定的功能,比如说UILabel,所有它的子类只有标签特定的东西。其他元素相同......

所以我真的需要能够做到以下几点:

MyView.property.methodSharedByAllUIViewSubclasses
MyImageView.property.someImageViewSpecificMethod
MyLabel.property.onlyLabelSpecificMethod

非常感谢任何有关如何在Swift中设计这种情况的帮助。

编辑: 我想使用协议和协议扩展来实现这一目标......

3 个答案:

答案 0 :(得分:2)

struct Property<T> {
    let property: T

    init(_ obj: T) {
        property = obj
    }
}

protocol PropertyDSL {
    associatedtype DSL
    var property: Property<DSL> { get set }
}

extension PropertyDSL {
    var property: Property<Self> {
        get {
            return Property(self)
        }
        set { }
    }
}

extension UIView: PropertyDSL {}

extension Property where T: UIView {
    func methodSharedByAllUIViewSubclasses() {
    }
}

extension Property where T: UIImageView {
    func someImageViewSpecificMethod() {
    }
}

extension Property where T: UILabel {
    func onlyLabelSpecificMethod() {
    }
}

答案 1 :(得分:0)

您可以覆盖每个子类中的现有变量/函数

class MyView: UIView {

   var property: Bool {
        get {
            return false
        } set {

        }
    }
    func propertyFunction () {
        //methodSharedByAllUIViewSubclasses
    }
}


class MyImageView: MyView {

   override var property: Bool {
        get {
            return false
        } set {

        }
    }
    override func propertyFunction () {
        //someImageViewSpecificMethod
    }
}

class MyLabel: MyView {

   override var property: Bool {
        get {
            return false
        } set {

        }
    }
    override func propertyFunction () {
        //onlyLabelSpecificMethod
    }
}

答案 2 :(得分:-1)

在swift 3中,您可以创建扩展名,如下面的代码段所示,并为标准类添加一些其他属性,并根据您的需要在多个位置使用它。

extension UIView {
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
}

上面提到的扩展将允许你将cornerRadius添加到任何UIView或其继承UIView的子类,如UIImageView。

以下代码剪切的结果如下:

enter image description here

我希望这能帮助你实现你想要的目标。

相关问题