简体   繁体   中英

UITableView row separator cut off when updating cell

I have a grouped UITableView in which I display some car data in the second section. I load the image from a web server using SDWebImage . In its callback I resize the picture and update my image view.

However, as soon as I update my image view, the UITableView separator is cut off. For illustration purposes I've given the respective elements background colors When the image is not loaded yet, it looks like this:

行分隔符可见

When the image is updated, it looks like this

在此处输入图片说明

Notice that the row separator is somehow cut off between the UITableView cells even though no subview (the UIImageView ) is hiding it.

Depending on the UITableView section the row height varies, so I've overwritten the heightForRowAtIndexPath UITableView delegate

 override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {

            return GFFloat(44)
        }
        else {

            return CGFloat(220)
        }

    }

Can someone tell me why the separators disappear and how I can fix this? I've read about reloading the next UITableViewCell when I update the image, but since I display a lot of cars, my app crashes when I try this.

Just add below method it will resolve separator issue.

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if cell.respondsToSelector("setSeparatorInset:") {
            cell.separatorInset = UIEdgeInsetsZero
        }
        if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
            cell.preservesSuperviewLayoutMargins = false
        }
        if cell.respondsToSelector("setLayoutMargins:") {
            cell.layoutMargins = UIEdgeInsetsZero
        }
    }

Solution for Swift 5

Add this to your controller:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
    if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
        cell.separatorInset = UIEdgeInsets.zero
    }
    if cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)) {
        cell.preservesSuperviewLayoutMargins = false
    }
    if cell.responds(to: #selector(setter: UIView.layoutMargins)) {
        cell.layoutMargins = UIEdgeInsets.zero
    }
}

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