简体   繁体   中英

Swift 3 UITableView cell seperator disappears when i remove cell subviews

I have an array type of string arrays and I print it to tableView within for loop.I know its a bad practice loop inside cellForRowAt indexPath : function but I don't have any solution.My Problem is every time I move my tableview on simulator,i insert more subviews on existing ones.it overwrites older ones and to prevent i use

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

but it deletes my cell seperators with my older cell labels.How can i remove only cell data not my seperator.

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

}

You can set tag to your label and scrollView object and check that inside loop like this.

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)!
}  

Tips: It is batter if you use interface builder to design your cell instead of adding UI element at run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM