UITableView 中的单元格重叠.一个地方有多个单元格 [英] Cells in UITableView overlapping. Many cells in one place
问题描述
我正在尝试使用随机数量的标签制作表格视图.一切正常,直到我尝试滚动它.比许多细胞出现在一个地方.它看起来像这样:
I'm trying to make table view with random numbers of labels in. Everything is working till I try too scroll it. Than many some of cells appear in one place. It looks like this:
为了在 viewDidLoad() 中设置随机行高,我把这个:
To make random row height in viewDidLoad() I put this:
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
这里是用随机行数写入随机数标签的代码:
The code going to write randoms number of labels with random number of lines is here:
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
有人知道如何修复它吗?我从一个星期开始就在寻找答案,但我没有找到任何关于它的信息...
Someone have some idea how to repair it? I'm looking for answer since one week and I did't find anything about it...
推荐答案
谢谢@Paulw11,prepareForReuse 正是我要找的.如果有人有类似的问题,答案是下面添加到 UITableViewCell 的代码:
Thank you @Paulw11, prepareForReuse was this what I was looking for. If someone have similar problem, the answer is code below added to UITableViewCell:
override func prepareForReuse() {
super.prepareForReuse()
for view in kindsNames.subviews { //take all subviews from your view
view.removeFromSuperview() //delete it from you view
}
}
干杯
这篇关于UITableView 中的单元格重叠.一个地方有多个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!