2

I have an old app source code that uses storyboard & xib without auto layout or size classes. Even though I am rewriting it from scratch, it would take some time as number of modules are too many. The immediate need is to fix the code that manually sets frame of UI elements by detecting screen size at runtime. So a code written this way places elements outside the safe area:

  self.controlBarBkg568h.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds) - tapBarBackgroundImage.size.height, CGRectGetWidth(self.view.bounds), tapBarBackgroundImage.size.height);

Since there are so many interface elements that are placed this way, I am wondering what is an easy way to fix the code that works on iPhone X?

Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131

1 Answers1

2

Use the safeAreaInsets property on UIView. This is a UIEdgeInsets object that describes the safe area for the current view. (Documentation)

In your specific case, you should be able to change your code to something like this:

self.controlBarBkg568h.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds) - tapBarBackgroundImage.size.height - self.view.safeAreaInsets.bottom, CGRectGetWidth(self.view.bounds), tapBarBackgroundImage.size.height);

If you have many views positioned this way, you are going to have to edit them all to respect the safe area. This is one of the downsides of manual layout — it's hard to change in the future (especially if there aren't any helper layout variables where you can edit many variables at once).

More documentation about positioning content relative to the safe area is available here: https://developer.apple.com/documentation/uikit/uiview/positioning_content_relative_to_the_safe_area

nathangitter
  • 9,607
  • 3
  • 33
  • 42
  • I think 0 would also need to replaced with self.view.safeAreaInsets.left – Deepak Sharma Oct 24 '17 at 18:38
  • @DeepakSharma You're right, but it depends on your use case. If you support landscape on iPhone X and want your views to respect the left and right safe areas, you would need to account for the safe areas. – nathangitter Oct 24 '17 at 18:41