代码之家  ›  专栏  ›  技术社区  ›  Ondrej Rafaj

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

  •  0
  • Ondrej Rafaj  · 技术社区  · 7 年前

    myView.property 。与许多子类相比,还有一些特定的功能,比如 UILabel 它的所有子类都只有标签特定的东西。其他元素也一样。。。

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

    如果您能在Swift中为这种情况提供设计帮助,我们将不胜感激。

    编辑:

    3 回复  |  直到 7 年前
        1
  •  2
  •   Zhang    7 年前
    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() {
        }
    }
    
        2
  •  0
  •   Berlin Raj    7 年前

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

    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
        }
    }
    
        3
  •  -1
  •   Dhaval Dobariya    7 年前

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

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

    以下是上述代码截取的结果:

    enter image description here

    我希望这将帮助你实现你想要的。