如果不使用故事板。
我想一个错误的标签添加到一个值不填写/保存的任何细胞。我的结论是,我不需要显示此逻辑,但问题出在所有的多个错误标签/多于一个的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
基于这个例子,我希望针对所有细胞的红色圆圈,而是,它显示在最后一个单元格。为什么?
有几件事情错在这里:
例:
cell.contentView.addSubview(myLabel)
你加入一个静态的标签,一遍又一遍。
含义:只有最后一个单元格将显示它,因为只有一个标签(:
最好用一个函数来创建标签(工厂函数)
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
}