【问题标题】:UIView not initialised with modelUIView 未使用模型初始化
【发布时间】:2020-09-06 08:29:40
【问题描述】:

我正在以这种方式使用 cardModel 设置 UIView:

var cardModel : CardModel!{
    didSet{
        nameLabel.text = cardModel!.name
    }
}


init(frame: CGRect, cardModel: CardModel) {
    super.init(frame: frame)
    
    
    self.cardModel = cardModel
    
    setUpUI()
    
    setUpGestureRecognizers()
    
    setUpPlayer()
    
}

问题是变量cardModel didSet没有被调用我其实不知道为什么

【问题讨论】:

    标签: swift uiview


    【解决方案1】:

    didSet 未被调用,因为您在 init 中初始化 carModel。所以为了让它工作,你可以把carModel的初始化放在一个闭包中,如下所示:

    init(frame: CGRect, cardModel: CardModel) {
        super.init(frame: frame)
        
        ({ self.cardModel = cardModel })()
        
        //...
    }
    

    更多信息:Is it possible to allow didSet to be called during initialization in Swift?

    【讨论】:

      猜你喜欢
      • 2013-09-04
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 2011-03-23
      • 1970-01-01
      相关资源
      最近更新 更多