fragon
fragon

Reputation: 3471

How to remove UITableView section header separator

I would like to remove (or make them clearColor) UITableView's section header separators. Setting tableView.separatorStyle = .none doesn't work. I've also tried solutions from here, but none of them actually worked for me (maybe because the answers are pretty old). I still get this tiny separator below the section header.

I created the UITableView in Storyboard and add a UITableViewCell there. Then I set it as a header like this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerTableViewCell")
        return cell
    }

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 49
        }
        return 0
    }

Upvotes: 11

Views: 15957

Answers (4)

yaronalk
yaronalk

Reputation: 74

Turns out overriding layoutSubviews removes all the cell's separators, both section-related and cell-related.

@interface MyCustomCell : UITableViewCell

@end    

@implementation MyCustomCell

- (void)layoutSubviews {
    // don't call [super layoutSubviews]
    // can be left empty
    // does not harm other UI elements inside the contentView
}

@end

In multiple-cell sections, you may just want to only remove the Section-related separators (at the top of first cell and at the bottom of last cell), keeping inset, inter-cell, separators shown:

- (void)layoutSubviews {
    [super layoutSubviews];

    for (UIView *view in self.subviews) {
        if ([view isEqual:self.contentView]) continue;

        view.hidden = view.bounds.size.width == self.bounds.size.width;
    }
}

Upvotes: 0

Abhishek Mitra
Abhishek Mitra

Reputation: 3395

I have solved this by following way:

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

Upvotes: 0

iParesh
iParesh

Reputation: 2368

Try this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor.clear
    return headerView
}

Upvotes: 1

Nirav D
Nirav D

Reputation: 72440

Don't know why you are returning UITableViewCell in viewForHeaderInSection method so may be it is possible that is showing separator of that UITableViewCell. Try returning the contentView of cell instead of cell from viewForHeaderInSection method.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerTableViewCell")
    return cell.contentView
}

Upvotes: 12

Related Questions