23

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.

Amja
  • 1,315
  • 9
  • 25

2 Answers2

46

Check if you are only seeing this issue on iOS 15 and above. 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 >= 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.

Amja
  • 1,315
  • 9
  • 25
  • Thank you so much. This should be more widely linked to on the ~2018 era results on this problem which I bounced between for the past 2 hours, because those results get the most traffic. – monstermac77 Mar 05 '23 at 02:25
  • 1
    @monstermac77 feel free to do that to help people in the future :) – Amja Mar 06 '23 at 18:47
  • 1
    Just posted it in a couple places! Thanks again. https://stackoverflow.com/a/76337142/2611730 – monstermac77 May 26 '23 at 01:37
  • 1
    I logged in just to upvote this! As mentioned, this is the only answer that makes sense since iOS 15. – VTPete Jul 14 '23 at 14:38
9

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)
}
Şafak Gezer
  • 3,928
  • 3
  • 47
  • 49