繁体   English   中英

Swift UILabel子视图未更新

[英]Swift UILabel Subview not updating

我有一个UICollectionView的标头。 此标头包含一个UILabel。 我通过通过委托调用函数updateClue来更新标签的文本值。

class LetterTileHeader: UICollectionViewCell {
  override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  var clueLabel: UILabel = {
    let label = UILabel()
    label.font = UIFont.systemFont(ofSize: 16)
    label.text = "HELLO"
    label.textColor = UIColor.white
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
  }()

  func setupViews() {
    backgroundColor = GlobalConstants.colorDarkBlue
    addSubview(clueLabel)

    clueLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    clueLabel.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
    clueLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    clueLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
  }

  func updateClue(clue: String) {
    clueLabel.text = clue
    debugLabel()
  }

  func debugLabel() {
    print(clueLabel.text)
  }

函数debugLabel将使用来自updateClue的更改后的文本进行打印。 但是屏幕上的标签不会更新。 我想念什么? 我尝试使用DispatchQueue.main.async块更改其中的标签文本,但仍然没有任何更改。

UpdateClue函数是通过协议委托从另一个类触发的。

extension PuzzleViewController: WordTileDelegate {
  func relaySelectedWordId(wordId: String!) {
    selectableTiles.updateTileHeaderClue(wordId: wordId)
  }
}

谢谢。

更新:我已经知道发生了什么事。 每次我选择一个新单元格时都会创建此子视图。 调查为什么会这样。 即将更新。

我遇到的问题是由于此单元类已多次初始化。 我相信我看到的标签不是正在更新的当前标签,而是实例化的前一个标签。 我有一个新问题,但是如果我不知道,我可能会提出一个问题。

您有两个UILabel和/或两个LetterTileHeaders。 您要更新的不是屏幕上正在显示的那个。

一种证明这一点的方法是在let label = UILabel()之后的行上放置一个断点。 断点很可能会多次被击中。

另一种方法是查看调试器中的屏幕布局,找到要显示的UILabel的内存位置,然后在updateClue方法中放置一个断点,并将该标签的内存位置与正在屏幕上显示的位置进行比较。 。

遵循代码似乎是错误的,这意味着每次使用clueLble时,它将为您提供新鲜的UILable实例。

var clueLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.text = "HELLO"
label.textColor = UIColor.white
label.translatesAutoresizingMaskIntoConstraints = false
return label

}()

尝试这样做:

  1. 只需将上面的代码替换为var clueLabel = UILabel()

  2. 添加以下功能:

     override func awakeFromNib() { super.awakeFromNib() label.font = UIFont.systemFont(ofSize: 16) label.text = "HELLO" label.textColor = UIColor.white label.translatesAutoresizingMaskIntoConstraints = false backgroundColor = GlobalConstants.colorDarkBlue addSubview(clueLabel) clueLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true clueLabel.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true clueLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true clueLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true 

    }

  3. 删除setupViews()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM