当我在自定义 tableView 单元格中绘制一组 CGRect 时遇到问题,当单元格被重用时它们会重复显示,这不是我想要的。
这是我的 tableView Controller 中的 tableView(cellForRowAt indexPath:) 函数:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! CustomTableViewCell
cell.addBlock(item: itemArray[indexPath.row])
cell.itemTitle.text = itemArray[indexPath.row].itemTitle
return cell
}
这是我的 CustomTableViewCell 类中的函数:(使用 xib 文件创建)
func addBlock(item: Item) {
for i in 0 ..< item.numberOfBlocks {
let block = UIView()
block.frame = CGRect(
origin: CGPoint(
x: CGFloat(i) * 10,
y: 0
),
size: CGSize(
width: 10,
height: bounds.size.height
)
)
block.backgroundColor = UIColor.orange
self.addSubview(block)
}
}
我认为我根据 itemArray 项目中的 numberOfBlock 属性绘制每个单元格,但是当重复使用单元格时, block 将不会重新绘制... 我尝试在这里和其他地方搜索,但我找不到答案(很长一段时间),我是 swift 的新手,请耐心等待......非常感谢。
注意: 项目类别包括 2 个属性: 1. itemTitle:字符串, 2. numberOfBlocks: Int
最佳答案
我相信您遇到此问题是因为 let block = UIView()
在重用时未从单元格中删除。如果是,您可以尝试以下策略:
- 保留
CustomTableViewCell
类中的每个let block = UIView()
; - 实现
prepareForReuse()
方法并从 super View 中删除所有block
。
此步骤可确保重用的单元格不会受到先前状态的任何阻碍。
一些实现:
final class CustomTableViewCell: UITableViewCell {
private var blocks: [UIView] = []
override func prepareForReuse() {
super.prepareForReuse()
blocks.forEach { $0.removeFromSuperview() }
blocks = []
}
func addBlock(item: Item) {
for ... {
let block = UIView()
...
blocks.append(block)
}
}
}
关于ios - 当重复使用自定义 tableView 单元格时,相同的 subview 会重复显示(Swift 4.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49390942/