16

I have a simple tabbed application whose first tab is a UITableViewController. After populating some data, I noticed that the top of the table view overlaps the status bar.

I've tried messing with the edgesForExtendedLayout and similar settings, but have not found the magical combo. Does anyone know how to correct this?

Steps to reproduce:

  1. Create a new tabbed application
  2. Remove the first tab UIViewController and replace it with a UITableViewController
  3. Populate the UITableView with some data
  4. Run the application

Here's a couple screenshots of the setup and the issue: Xcode Storyboard UITableView overlapping status bar

Albert Bori
  • 9,832
  • 10
  • 51
  • 78

2 Answers2

31

Just modify the contentInset property of your table view, which can add some padding around your content. In viewDidLoad() add the following:

tableView.contentInset.top = 20

In Objective-C, you can't assign to the top directly, so do it like so:

self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

Of course it can be any arbitrary value, in this case, it is the height of the status bar.

József Vesza
  • 4,775
  • 3
  • 27
  • 42
  • 19
    Thanks. I'm surprised this isn't the default. (Apple should check for status bar and set it accordingly.) I settled with `tableView.contentInset.top = UIApplication.sharedApplication().statusBarFrame.height` because I don't like magic numbers :) – Albert Bori May 15 '15 at 20:41
  • And you're right about that. ;) Well the reason here is that (since iOS 7) views extend their edges for the full screen by default. If you embed your view in a navigation controller, you'll see that the navigation bar is taken into account automagically (called "top layout guide"). – József Vesza May 15 '15 at 20:42
  • you probably want to set scrollIndicatorInsets as well – Janneman May 07 '16 at 08:56
  • 1
    This doesn't really work so well for me. There is still no backing view so I cannot set the particular color I want there and anyway scrolling the tableview the content still overlaps status content.. – stonemonk Jan 13 '17 at 02:24
  • 1
    I don't know how but I tried this previously at that time it was not working not it's working well. – Mihir Oza May 08 '17 at 08:16
  • 1
    Setting contentInset did not work for my case in iOS 11. iPhone 8. any other way? when scrolling table contents go under the status bar. – karim Mar 08 '18 at 10:26
  • does not work. iOS 11. – William Yang Apr 20 '18 at 04:47
4

As suggested in comments, one way is to (in Swift 3):

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.contentInset.top = UIApplication.shared.statusBarFrame.height
}

But that not as clean. It is better to embed the UITableViewController in a UINavigationController (Editor > Embed In > Navigation Controller) and uncheck "Shows Navigation Bar" in the inspector. No tweaking needed!

sanmai
  • 29,083
  • 12
  • 64
  • 76