Swift 3 删除单元格子视图时 UITableViewcell 分隔符消失

Swift 3 UITableView cell seperator disappears when i remove cell subviews

我有一个字符串数组的数组类型,我将它打印到 tableView 中 for loop.I 知道它在 cellForRowAt indexPath: 函数中是一个不好的循环,但我没有任何 solution.My 问题是每次我在模拟器上移动我的 tableview 时,我都会在现有 ones.it 上插入更多子视图覆盖旧的并防止我使用

for view in cell.subviews {
        view.removeFromSuperview()
}

但是它删除了我的旧单元格分隔符labels.How我可以只删除单元格数据而不是我的分隔符吗?

func tableView(_ tableView: UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell {

    var cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
    //print(cell.subviews)
    for view in cell.subviews {
        view.removeFromSuperview()
    }


    for i in 0..<globalHeaderStructArray.count{
        var newLabel = UILabel(frame: CGRect(x:xCoordination, y:10, width:Double(globalHeaderStructArray[i].width)!, height:30.0))
        newLabel.font = UIFont(name: "Avenir", size: 17.0)
        newLabel.textColor = UIColor.darkGray
        newLabel.text = "\(globalDataArray[indexPath.row][i])"

        var scrollview = UIScrollView(frame: cell.bounds)
        scrollview.contentSize = CGSize(width:cell.bounds.width * 5, height:cell.bounds.height) // will be 5 times as wide as the cell
        scrollview.isPagingEnabled = true

        cell.contentView.addSubview(scrollview)
        cell.addSubview(newLabel)
        xCoordination += Double(globalHeaderStructArray[i].width)!
    }
    xCoordination = 0.0

    return cell

}

您可以将 tag 设置为您的标签和 scrollView 对象并像这样检查内部循环。

for view in cell.subviews {
    if view.tag == 101 || view tag == 102 {
        view.removeFromSuperview() 
    }
}


for i in 0..<globalHeaderStructArray.count{
    var newLabel = UILabel(frame: CGRect(x:xCoordination, y:10, width:Double(globalHeaderStructArray[i].width)!, height:30.0))
    newLabel.font = UIFont(name: "Avenir", size: 17.0)
    newLabel.textColor = UIColor.darkGray
    newLabel.text = "\(globalDataArray[indexPath.row][i])"
    newLabel.tag = 101

    var scrollview = UIScrollView(frame: cell.bounds)
    scrollview.contentSize = CGSize(width:cell.bounds.width * 5, height:cell.bounds.height) // will be 5 times as wide as the cell
    scrollview.isPagingEnabled = true
    scrollview.tag = 102

    cell.contentView.addSubview(scrollview)
    cell.addSubview(newLabel)
    xCoordination += Double(globalHeaderStructArray[i].width)!
}  

提示:如果你使用界面构建器来设计你的单元格,而不是在运行时添加UI元素,那就更好了。