Sunday, January 14, 2018

Autoresizing and Constraints to Safe Area

Recently one issue has troubled me for several days. Finally I just figured it out. I think it is worthwhile to make a note about my experience.

I have an app with several tab views, all displaying similar data in table view. I tried to add search feature for the app. The way to add search controller for iOS 11 and iOS 10 is different. For iOS 11, the search controller is added to navigation controller while the search controller is added to table view's header for iOS 10. My test of iOS 11 works great. However, the test for iOS 10 presented an issue.

In the first tab view, the search works well, but not in the second one. The issue is that the content of table view is shifted up about 40 pixels in the second tab.

Here is the search bar at initial status:

Tap on search bar to start search. Notice that the content of table view is shifted up 40, about half of the first row is behind the search bar.

Even worse, I could not see the search bar if I select a row to the next screen and back to the main screen. The search bar is moved up, not in reachable view.

The search function in the first tab view works without this issue. Therefore, the best way is to compare the difference between two tab view controllers. There are not any major difference. I tried to disable some codes in viewDidLoad, viewWillAppear, and viewDidAppear to make them behaviour the same. Still I could not resolve the issue.

Finally, I noticed there is a difference in storyboard. The table view of the first tab is using autoresizing.

while the second tab's view controller uses constraints for its table view!

I removed four constraints and set autoresizing for the table view of the second tab. With this change, the search feature works well as expected.

It seems that autoresizing for iOS 11 is almost as same as four constraints to its safe area (which is introduced in iOS 11 but not exist in iOS 10). Even it would fall back to previous layout guide, it seems not working in the same way for table view in this case. For old iOS back from 11, try to not use safe area as reference for table view constraints.

Test for all supported iOS versions is very important!