【发布时间】:2017-04-01 09:33:02
【问题描述】:
我正在尝试使用随机数量的标签制作表格视图。一切正常,直到我尝试滚动它。比许多细胞出现在一个地方。它看起来像这样:
为了在 viewDidLoad() 中随机设置行高,我这样写:
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
编写随机行数的标签的代码在这里:
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
有人知道如何修复它吗?一个星期以来我一直在寻找答案,但我没有找到任何关于它的信息......
【问题讨论】:
-
单元格被重复使用。每次获取单元格时都在添加标签,但不会删除任何旧标签。无论如何,您可能不应该直接在
cellForRow(at:)中添加标签;它应该是你的 UITableViewCell 子类中的一个方法。您可能需要在prepareForReuse中跟踪添加和删除的标签 -
@Paulw11 谢谢! 'prepareForReuse' 就是我要找的 :)
标签: ios uitableview scroll swift3 overlapping