我有一个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
}()
尝试这样做:
只需将上面的代码替换为
var clueLabel = UILabel()
添加以下功能:
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
}
删除
setupViews()