簡體   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