我需要将 UILabels 添加到 UITableViewCell,但它是动态的,第一个单元格可以有 1 个标签,第二个单元格可以有 4 个标签,我事先不知道。所以我尝试了这个
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell: ReviewTableViewCell = reviewTableView.dequeueReusableCell(withIdentifier: "Review", for: indexPath) as! ReviewTableViewCell
var reviewObj:Review!
reviewObj = reviewArray[(indexPath as NSIndexPath).row]
let viewsAdded = commentViewsAddedDict[indexPath.row]
if(viewsAdded == nil)
{
for comment in reviewObj.commentArray
{
let label1 = UILabel()
label1.text = “text1”
label1.textColor = UIColor(hexString: "#333333")
let label2 = UILabel()
label2.text = “text2”
label2.numberOfLines = 0
label2.sizeToFit()
label2.textColor = UIColor(hexString: "#666666")
let label3 = UILabel()
label3.text = "----------------------------------------------------------------------"
label3.textColor = UIColor(hexString: "#eeeeee")
cell.stackView1.addArrangedSubview(label1)
cell.stackView1.addArrangedSubview(label2)
cell.stackView1.addArrangedSubview(label3)
}
commentViewsAddedDict[indexPath.row] = true
}
return cell
}
但是发生了什么,之前添加的 View 没有被删除,并且它再次尝试添加新 View 。
所以我想知道,什么是有效的方法来做到这一点。 其次,我哪里出错了。
问候 兰 git
最佳答案
您正在使用commentViewsAddedDict
以确定是否已添加行。但是否添加这些标签并不是表中行的函数,而是重复使用的单元格的函数。
所以,我建议:
消除这个
commentViewsAddedDict
逻辑;和移动有关已将多少标签添加到
ReviewTableViewCell
的逻辑.
所以,你最终可能会得到:
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = reviewTableView.dequeueReusableCell(withIdentifier: "Review", for: indexPath) as! ReviewTableViewCell
var reviewObject = reviewArray[(indexPath as NSIndexPath).row]
cell.updateLabels(for: reviewObject)
return cell
}
在 ReviewTableViewCell
:
func updateLabels(for reviewObject: ReviewObjectType) {
// add label if needed
// update label `text` if needed
// remove any labels that need to be removed
}
具体说明 updateLabels
中的逻辑有点困难因为问题中提供的代码片段不清楚,但基本思想是 ReviewTableViewCell
应该跟踪其标签是否已添加,并基于 reviewObject
,决定是否需要添加标签、更新现有标签或删除此特定 reviewObject
不需要的任何标签。但所有这些“标签状态”逻辑都是单元格的函数(可以重用),而不是单元格对应的表中哪一行的函数。
关于swift - 动态添加子View到UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683959/