Search code examples
iosxcodeautolayout

Auto Layout constraints for container view inside UITableView header broken for different devices


I have an issue that makes no sense to me. I have the following setup:

| UITableView |

|| UITableView header ||

||| UIView |||

So inside my UITableView header I have a container view that has leading, trailing and top constraints to its superview. Everything is set up correctly for my test device size (which is iPhone 8). If I change the test device to iPhone 8 Plus I get a strange offset for my trailing constraint - 39pt to the right edge, which is exactly the difference between iPhone 8 plus width in points and iPhone 8.

When I switch between devices in Xcode and see that the trailing constraint is not correct I just make an adjustment myself (change trailing to 1 and then back to 0) and the problem goes away for the particular device.

Initially I thought it is bug in Xcode but when I tested on a device the problem is still there.

I tried setting up a new view controller and adding the same elements but with no effect.

I am attaching screenshots to make my issue clearer.

Before: Adjusting the desired constraints

Using the desired trailing constraint in iPhone 8 size

After: Switching to a device with different size

Trailing constraint is broken for all other device sizes


Solution

  • At first I accepted DonMag's answer (thanks for your time) as this really seemed to be an Xcode Interface Builder bug. As I investigated further when having the scenario I mentioned auto layout constraints are not updating the layout when I need it hence not giving me the right view.bounds.

    I tried getting it in viewDidLayoutSubviews() without success as well - it was still giving me a size that suits another device.

    What did the trick was calling view.layoutIfNeeded() before working with view's bounds. What it does is to update the view's layout immediately. As a result you can access the desired view's bounds.