如何将一个子视图添加到所有UITable细胞

问题描述 投票:0回答:1

如果不使用故事板。

我想一个错误的标签添加到一个值不填写/保存的任何细胞。我的结论是,我不需要显示此逻辑,但问题出在所有的多个错误标签/多于一个的tableView的细胞。

我创建这个viewLabel重用:

struct Label {
    static let errorLabel: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        label.text = "!"
        label.layer.cornerRadius = label.frame.height / 2
        label.backgroundColor = UIColor.red
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .center
        label.textColor = UIColor.white
        label.font = UIFont(name: "CircularStd-Black", size: 14)
        label.clipsToBounds = true
        return label
    }()
}

内部cellForRowAt:

// I'm using detailTextLabel
let cell = UITableViewCell(style: .value1, reuseIdentifier: cellId)
cell.addSubview(Label.errorLabel)
// [...] constraints for Label.errorLabel
return cell

基于这个例子,我希望针对所有细胞的红色圆圈,而是,它显示在最后一个单元格。为什么?

swift uitableview swift4 swift4.2
1个回答
1
投票

有几件事情错在这里:

  1. 您应该只添加到单元格内容查看。 (https://developer.apple.com/documentation/uikit/uitableviewcell/1623229-contentview

例:

cell.contentView.addSubview(myLabel)
  1. 更好的重用将是一次添加,标签。这可以在Interface Builder或init或awakeFromNib来完成。这样,再利用的效率会更高。
  2. 这是您所看到的主要问题:

你加入一个静态的标签,一遍又一遍。

含义:只有最后一个单元格将显示它,因为只有一个标签(:

最好用一个函数来创建标签(工厂函数)

static func createLabel() -> UILabel {
  let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        label.text = "!"
        label.layer.cornerRadius = label.frame.height / 2
        label.backgroundColor = UIColor.red
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .center
        label.textColor = UIColor.white
        label.font = UIFont(name: "CircularStd-Black", size: 14)
        label.clipsToBounds = true
        return label
}
© www.soinside.com 2019 - 2024. All rights reserved.