iOS 15: Remove empty space before cells in UITableView

Viewed 4143

I am using UITableView for a multi-section list. The issue I am seeing is a space above the cells of each section, even if I set tableView(_:heightForHeaderInSection:) to be 0. This occurs even when there is only one section and I set tableView(_:viewForHeaderInSection:) to be nil.

I have tried all other answers on StackOverflow relating to inset overrides/edge expanding but none have worked.

Example:

Screenshot of iOS table view. Above each section header is a gap which is the same colour as the table background.

2 Answers

Check if you are only seeing this issue on iOS 15. If so, this may be caused by the newly introduced UITableView.sectionHeaderTopPadding property. You will need to set this value to 0 in order to remove the spacing before section headings:

let tableView = UITableView()
tableView.sectionHeaderTopPadding = 0

// Etc.

This property is only available in iOS 15 so you will need an API check if building for earlier versions.

If you're not on iOS 15, this question has most of the answers to this issue.

Another approach is to set the sectionHeaderTopPadding value found in UITableView's UIAppearance proxy, which ensures that the value will be applied to every instance of UITableView in your application:

if #available(iOS 15.0, *) {
    UITableView.appearance().sectionHeaderTopPadding = CGFloat(0)
}
Related