swift - 如何仅以编程方式将控件添加到 tableview 单元格一次

标签 swift uitableview

override func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell    {let cell = tableView.dequeueReusableCell (withIdentifier: "cell", for: indexPath)
 let customerNameLabel = UILabel()
 customerNameLabel.frame = CGRect (x: 10, y: 5, width: 150, height: 40)
 customerNameLabel.textColor = .black
 customerNameLabel.text = "Customer Name\ (indexPath.row)"
 cell.contentView.addSubview(customerNameLabel)
 return cell      
}

在尝试向单元格添加标签时,即使在滚动 tableView 时它也会添加次数,但我只需要添加标签一次并重新使用它

最佳答案

您需要创建一个自定义 UITableViewCell 并将您的标签添加到它。

因为在您提供的代码中,每次重复使用单元格时,您都会向单元格添加 UILabel()。

关于swift - 如何仅以编程方式将控件添加到 tableview 单元格一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072715/

相关文章:

ios - 取消选择时如何阻止 UITableViewCell 闪烁为白色?

iphone - 为小型固定大小的 UITableView 禁用单元格重用

swift - UIStackView 未按预期显示

ios - 使用自定义维度在初始化时布局单元格 subview

ios - 多维数组和 UITableView

ios - 如何实现类似于 Facebook 或 Instagram 的新闻评论页面

ios - 如何将一个 UIStoryboard 场景与 UITableViewController 和 resultsTableViewController 与 UISearchController 配合使用?

ios - Tableview 刷新/重新加载就像在 iOS5 的提醒应用程序中一样

swift - 给 UISegmentedControl 添加 NSLayoutConstraints 导致 UISegmentedControl 消失

ios - DateFormatter 返回时区的意外日期