bnassler
bnassler

Reputation: 651

UITableView contentOffset for headerView misaligned

My headerView in my tableView should go all the way to the top of the device. On iPhone X the same so the notch goes over it.

Then when I scroll my tableView I use scrollViewDidScroll(scrollView: UIScrollView) to change the height of my headerView to add scrollView.contentOffset.y so it goes all the way.

It works as soon as I scroll but not initially.

So it looks like this:

enter image description here

and this on the X

iPhone X

How to I get rid of the white area so the grey one goes under it when it loads?

I tried a couple places but it seems the tableView still has no contentOffsets... I think I am missing something fundamental here how "it should be done"...

Update: ViewHierarchy, blue is tablewView, but then I get this distance there...

enter image description here

Upvotes: 0

Views: 1133

Answers (2)

bnassler
bnassler

Reputation: 651

Ok I found it. So it has to do with the change with safe areas introduced for the iPhone X.

There are two possibilities, it really depends on the storyboard setup:

If you are using a storyboard and your base is a UIViewController with a tableView placed inside it:

Then fixing the auto layout is the answer:

When safe area is enabled, click on your topmost view and create the top constraint is relative to the superView with constant 0. By default it wants to protect the safe area so it is set relative to the safe area.

If you are using a UITableViewController template (e.g. default when dragging out a navigation controller - tableview combo (my case))

Here there are no constraints that can be set. Hence it didn't work for me (see above). To fix it click on the root tableView, select the size inspector and then set "content insets" to "never".

Or programmatically in viewDidLoad:

self.tableView.contentInsetAdjustmentBehavior = .never

Upvotes: 3

leedex
leedex

Reputation: 1013

Are you making your tableview in storyboard?

in viewDidLoad try anchoring your tableview:

tableview.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

Upvotes: 0

Related Questions