我正在用 Swift 3 编写一个涉及 UITableView 的应用程序。我正在务实地创建我的表格 View 单元格。我遇到的问题是单元格的标签文本在 .reloadData() 函数之后仍然存在。是否有在使用前清除单元格中所有元素和格式的功能?我正在通过代码实例化 UILabel 并且无法跨迭代访问它。不幸的是,我已经花了很多时间以编程方式创建表,所以我想尽可能避免返回并创建单元格类。
我打算使用这样的函数:
var label: UILabel
if reloadCount > 0 {
//clear all formatting from the cell
}
label = UILabel(frame: CGRect(x: 30, y: 0, width: self.screenWidth - 100, height: 50))
label.textAlignment = .center
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.textColor = UIColor(red: 127.0/255, green: 140.0/255, blue: 142.0/255, alpha: 1.0)
label.font = UIFont(name: "Tahoma", size: CGFloat(22))
label.numberOfLines = 0
label.tag = Int(self.thoughtFeed[indexPath.row].dbId!)!
label.text = thoughtFeed[indexPath.row].thoughtText!.fromBase64()
label.isUserInteractionEnabled = true
label.addGestureRecognizer(labelTap)
cell.addSubview(label)
非常感谢您的帮助。
最佳答案
您需要以某种方式“记住”UILabel
并重新使用或删除它。既然你说你不想继承 UITableViewCell
你可以使用标签来获取对你的标签的引用。在您的 cellForRowAtIndexPath
中执行如下操作:
if let label = cell.viewWithTag(42) as? UILabel {
// now you have a reference to the existing label.
// Just update the text (or whatever you need to do)
} else {
label = UILabel(frame: CGRect(x: 30, y: 0, width: self.screenWidth - 100, height: 50))
// add a tag so we can remember it when we dequeue a cell later
label.tag = 42
cell.addSubview(label)
}
关于ios - 如何在重用之前清除从 UITableViewCell 以编程方式创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077528/