具有动态创建高度的单元格重叠



嗨,我是IOS开发人员的新手,我更熟悉web开发人员。我遇到了一个问题,我的单元格最初是按照我期望的方式呈现的,但在滚动到屏幕底部并滚动回屏幕顶部后,我注意到单元格开始相互重叠。在阅读了其他堆栈溢出的帖子后,我开始认为这与我如何创建单元格有关。我试图在一个带有for循环的单元格中创建多个标签,类似于使用PHP for web dev的人,我想知道这是否是正确的方法/这是否是可能的原因。

for i in 0...bars.count-1 {
var barLabelView:UIView = UIView()
var barLabel:UILabel = UILabel()
barLabelView.frame = CGRect(x: 20, y: CGFloat(20 + (70 * i)), width: barView.frame.width-40, height: 50)
barLabelView.backgroundColor = UIColor(displayP3Red: 27/255.0, green: 99/255.0, blue: 222/255.0, alpha: 1)
barLabelView.layer.cornerRadius = 10
barLabel.frame = CGRect(x: 0, y: 0, width: barLabelView.frame.width-10, height: 50)
barLabel.text = bars[i]
barLabel.textAlignment = .center
barLabel.numberOfLines = 0
barLabel.font = UIFont(name: "Chalkboard SE", size: 15)
barView.addSubview(barLabelView)
barLabelView.addSubview(barLabel)
}

这里还有我如何设置单元格的高度:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let crawlNameText = self.posts[indexPath.row].text
let size = CGSize(width: view.frame.width - 40, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedCrawlNameFrame = NSString(string: crawlNameText).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], context: nil)

let bars = posts[indexPath.row].bars.components(separatedBy: ", ")
let buds = posts[indexPath.row].buds.components(separatedBy: ", ")
if (self.posts[indexPath.row].type == "crawl") {
var cellHeightP1 = CGFloat(estimatedCrawlNameFrame.height + 110 + 20 + 20 + 20 + 40 + 60)
var cellHeightP2:CGFloat = CGFloat( 80 * bars.count)
var cellHeightP3:CGFloat = CGFloat( 80 * buds.count)
var cellHeight = cellHeightP1 + cellHeightP2 + cellHeightP3
return cellHeight
} else {
return estimatedCrawlNameFrame.width + 110 + 20
}
}

这是我的cellForRowAt函数

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = nfTV.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! newsFeedCell
// Im guessing I would set the cell to nill here to clear the buttons I made
cell.setPost(post: posts[indexPath.row])
if (cell.profilePic != nil){
cell.profilePic.layer.cornerRadius = cell.profilePic.bounds.height / 2
cell.profilePic.clipsToBounds = true
}
cell.backgroundColor = UIColor.lightGray
print("made it here")
print(indexPath.row)
cell.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)

return cell
}

我读到在重复使用之前我可能必须清除我的单元格,但我不知道如何将单元格设置为零。我还想知道使用集合视图是否会更好,但我不知道这和表视图之间的区别。感谢您的帮助或建议。

我回答了自己的问题,但我想我会把这个问题留着,以防它对未来的任何人都有帮助

我在cellForRowAt函数的注释处添加了以下几行代码,以删除按钮

for v in cell.barView.subviews{
v.removeFromSuperview()
}
for v in cell.budsView.subviews{
v.removeFromSuperview()
}

这个问题是由一些单元格比其他单元格有更多的按钮引起的,所以按钮较少的单元格被渲染为有多余的按钮,使其看起来像是重叠的,但实际上它只是回收的按钮。

最新更新