miss Gbot
miss Gbot

Reputation: 373

Why TableView added invisible separator on some rows?

enter image description here

This separator is invisible on normal view. I set all separator layer to red and had seen it. If I set tableView.separatorStyle = .none, this separator, and normal separator not added to cell. Easy to reproduce:

  1. Add TableViewController

  2. Set cell enter image description here

  3. Add code to cell:

    override func layoutSubviews() {
        super.layoutSubviews()
        let separators = self.subviews.filter({$0.bounds.height < 1 && $0.bounds.height > 0})
        separators.forEach({
            $0.layer.backgroundColor = UIColor.red.cgColor
        })
    

What is it?

Upvotes: 0

Views: 129

Answers (2)

miss Gbot
miss Gbot

Reputation: 373

Ok, I understand. These invisible views are not separators, they are created when I make my margins is relative.

Upvotes: 1

ciccioska
ciccioska

Reputation: 1291

The correct way for replace the separator, or show it in some way or show one different for each section is this:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case 1:
            cell.separatorInset = UIEdgeInsetsMake(0.0, tableView.bounds.size.width, 0.0, 0);
            let additionalSeparatorThickness = CGFloat(1)
            let additionalSeparator: UIView = UIView(frame: CGRect(x: 15.0, y: cell.frame.size.height - additionalSeparatorThickness,
                                                                   width: cell.frame.size.width-30.0,
                                                                   height: additionalSeparatorThickness))
            additionalSeparator.backgroundColor = UIColor.Red
            cell.addSubview(additionalSeparator)
        default:
            break;
        }
    }

In the sample above(with some customization for the line width, height, ecc), for all the rows in the section 1 we draw a red line separator and in the other sections we don't show anything.

Upvotes: 1

Related Questions