我有这个功能:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
let label = UILabel(frame: CGRect(x: 100, y: 14, width: 400, height: 30))
label.text = "\(data[indexPath.row])"
label.tag = indexPath.row
cell.contentView.addSubview(label)
return cell
}
好吧,通过这个函数,我动态地添加了一个行列表。 为什么是动态的?因为,列数取决于数据。 不要专注于此。
该列表有 244 个元素。 结果显示正常,但是一旦我开始滚动,我得到这个:
如何动态添加元素而不出现此错误?
最佳答案
细胞得到重用。您不断向每个单元格添加越来越多的标签。
正确的解决方案是创建一个包含所需标签的自定义单元格类。然后只需在 cellForRowAt
中设置该标签的文本。不要在 cellForRowAt
中创建和添加 subview 。
但请记住,您可能只想使用 UITableViewCell
提供的 textLabel
属性。无需自定义单元格或您自己的标签。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
cell.textLabel?.text = "\(data[indexPath.row])"
return cell
}
关于swift - 将 View 动态添加到单元格会在表格中产生问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49697770/