Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last border of the last cell in UITableView?

People also ask

How do I delete a cell in UITableView?

So, to remove a cell from a table view you first remove it from your data source, then you call deleteRows(at:) on your table view, providing it with an array of index paths that should be zapped. You can create index paths yourself, you just need a section and row number.

What is IndexPath in Tableview Swift?

Swift version: 5.6. Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section.


The best solution is add a footer view. The following code hide the last cell's line perfectly:

Objective-C

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1)];

Swift 4.0

tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1))

In iOS 7 there is an easier solution. Supposing cell is your last cell:

cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);

Updated on 9/14/15. My original answer become obsolete, but it is still a universal solution for all iOS versions:

You can hide tableView's standard separator line, and add your custom line at the top of each cell. The easiest way to add custom separator is to add simple UIView of 1px height:

UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 1)];
separatorLineView.backgroundColor = [UIColor grayColor];
[cell.contentView addSubview:separatorLineView];

To date, I subscribe to another way for hiding extra separators below cells (works for iOS 6.1+):

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

This works for me in iOS 7 and 8:

cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(tableView.bounds));

NOTE: be careful about using tableView.bounds as it sometimes reports the wrong value depending on when you call it. See Reporting incorrect bounds in landscape Mode


Add this line of code in viewDidLoad().

tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.001))

This make sure the last separator will be replaced and replaced (invisible) footer view will not occupy any extra height. Since the footer view's width will be managed by UITableView, so you can set it to 0.


Extension based solution for Swift 4, tested on iOS 12

I noticed that setting a empty view of height = 1 also removes the separator of the last visible cell however setting height = 0 just removes the separator of the empty cells

extension UITableView {
    func removeSeparatorsOfEmptyCells() {
        tableFooterView = UIView(frame: .zero)
    }

    func removeSeparatorsOfEmptyCellsAndLastCell() {
        tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: 1)))
    }
}