【问题标题】:Setting values of a class for example UIButton设置类的值,例如 UIButton
【发布时间】:2018-06-05 21:08:17
【问题描述】:

我缺乏一些基本的了解。

今天我想继承一些 UIView 并且我查看了 UIButton 定义,但我不知道它是如何工作的。

在 UIButton 定义中有如下属性:

open var adjustsImageWhenHighlighted: Bool 

open var adjustsImageWhenDisabled: Bool 

当使用 UIButton 时,设置 UIButton 的值并不重要,它总是以与 tableView 或任何其他 UIKit 类相同的正确方式进行配置。

我做了一个例子:

class customView: UIView {
        var shouldSetupConstraints = true
        var addAdditionalSpacing = true

        var elements: [String]? {
            didSet{
                if addAdditionalSpacing == false {
                    doSomething()
                }
            }
        }
        func doSomething() {
        }

        override init(frame: CGRect) {
            super.init(frame: frame)
            setUpLayout()
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }

        override func updateConstraints() {
            if(shouldSetupConstraints) {
                // AutoLayout constraints
                shouldSetupConstraints = false
            }
            super.updateConstraints()
        }

        func setUpLayout() {

        }
    }

使用自定义视图:

lazy var customV: CustomView = {
    let v = CustomView()
    v.addAdditionalSpacing = true
    v.elements = ["One","Two"]
    return v
}()

lazy var customV2: CustomView = {
    let v = CustomView()
    v.elements = ["One","Two"]
    v.addAdditionalSpacing = true
    return v
}()

因此,如果我使用 CustomView 设置它的顺序会有所不同,我理解为什么,但我不明白我必须以哪种方式设计我的类,以便我可以随时设置值,除了如果 didSet 配置不同。为什么 UIButton 中的属性没有任何设置器,在这种情况下如何设置值?

我们也感谢任何指向文档的链接。

【问题讨论】:

    标签: swift uiview uibutton uikit subclassing


    【解决方案1】:

    首先,在 UIButton 中,您可以像这样控制现有属性的 didSet 属性观察器:

    override var adjustsImageWhenDisabled: Bool {
        didSet {
            doStuff()
        }
    }
    

    其次,在你的类场景中,你可能会考虑在构造函数中传递参数:

    init(shouldSetupConstraints: Bool = true, var addAdditionalSpacing = true)
    

    这样,您可以随时使用这些属性。

    如果这有帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2017-03-23
      相关资源
      最近更新 更多