swift - 将 View 动态添加到单元格会在表格中产生问题

标签 swift uitableview tableview

我有这个功能:

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 个元素。 结果显示正常,但是一旦我开始滚动,我得到这个:

enter image description here

如何动态添加元素而不出现此错误?

最佳答案

细胞得到重用。您不断向每个单元格添加越来越多的标签。

正确的解决方案是创建一个包含所需标签的自定义单元格类。然后只需在 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/

相关文章:

ios - 如何将现有对象保存到 Core Data

swift - 在 Swift 中替换字符串中的特定字符

导航 Controller 转换上的 iOS 黑线

ios - 具有动态 subview 堆栈的自定义单元格

ios - 图像不是从一个 VC 到另一个 VC

javafx - 在 tableView javafx 中进行多选

ios - 如何捆绑 Realm 文件

ios - UILabel 在圆形自定义 UIView 中不可见

ios - NSFetchedResultsController 正在删除行而不是在更新核心数据后更新它们

iphone - iOS App 中的按钮不会显示