我试图用随机数量的标签制作表格视图。一切正常,直到我尝试滚动它。比许多细胞出现在一个地方。它看起来像这样:
要在viewDidLoad()中创建随机行高,我把它放在:
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
用于编写randoms代码的随机行数的代码如下:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HarvestPlan", for: indexPath) as! HarvestPlanCell
let currentSpecies = harvestPlan[indexPath.row]
var kindLabels = [UILabel]()
cell.kindsNamesView.bounds.size.width = 100
for kind in currentSpecies.kinds {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.text = kind.fullName
label.bounds.size.width = 100
label.sizeToFit()
label.bounds.size.width = 100
cell.kindsNamesView.addSubview(label)
kindLabels.append(label)
}
var previous: UILabel!
for label in kindLabels {
label.widthAnchor.constraint(equalToConstant: 100).isActive = true
label.heightAnchor.constraint(equalToConstant: label.bounds.height).isActive = true
label.leadingAnchor.constraint(equalTo: cell.kindsNamesView.leadingAnchor).isActive = true
if previous == nil {
label.topAnchor.constraint(equalTo: cell.kindsNamesView.topAnchor).isActive = true
}
if previous != nil {
label.topAnchor.constraint(equalTo: previous.bottomAnchor).isActive = true
}
if label == kindLabels.last {
label.bottomAnchor.constraint(equalTo: cell.kindsNamesView.bottomAnchor).isActive = true
}
previous = label
}
return cell
有人知道如何修复它吗?我已经找了一个星期以来的答案而且我找不到任何关于它的信息......
答案 0 :(得分:0)
谢谢@ Paulw11,prepareForReuse就是我要找的。如果有人有类似的问题,答案是下面的代码添加到UITableViewCell:
override func prepareForReuse() {
super.prepareForReuse()
for view in kindsNames.subviews { //take all subviews from your view
view.removeFromSuperview() //delete it from you view
}
}
干杯