【问题标题】:Swift public var with default value and run didSet for that default value [duplicate]具有默认值的 Swift public var 并为该默认值运行 didSet [重复]
【发布时间】:2016-09-19 11:17:14
【问题描述】:

我的 Swift 类如下所示:

class FavoriteView: UIView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    convenience init() {
        self.init(frame: CGRectZero)
    }
    private func commonInit() {
        // init something
    }

    // MY PROBLEM IS HERE
    var favoriteCount: Int = 0 {
        didSet {
            // update the view
        }
    }
}

逻辑是每当favoriteCount 设置为新值时,didSet 中的代码就会运行。

运行良好。但问题是代码(didSet)不是第一次运行。我的意思是当一个新的FavoriteView 实例被初始化时,我假设它也会运行,但事实并非如此。

有什么方法可以第一次运行该代码(didSet)。

谢谢!

【问题讨论】:

    标签: ios swift initialization


    【解决方案1】:

    didSet 观察者未使用默认值调用,以及在 init 方法中设置属性时未调用它(由于 self 尚未初始化)。您可以编写分离方法updateView 并在init 方法 中调用它didSet 观察者。

    private func commonInit() {
        updateView()
        // init something
    }
    
    // MY PROBLEM IS HERE
    var favoriteCount: Int = 0 {
        didSet {
            updateView()
        }
    }
    
    func updateView() {
        //code that you wanted to place in observer
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多