1

I have a UIView called headerview which I use like a NavigationBar. It has a constant size of 60 and top/left/right layout constraints which are 0. It looks okay for all devices except iPhone X because of safe area layout. If I change size to 90, It looks okay on iPhone X but now It looks wrong on other devices. I calculate height of safe area with below code and add it to height but now It looks small in other devices. What is the best approach to fix this problem?

    if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    CGFloat topPadding = window.safeAreaInsets.top;
    self.headerViewHeight.constant = 46 + topPadding;
}
Mr Some Dev.
  • 315
  • 4
  • 19

3 Answers3

4

Try this one. Check the phone is iPhoneX or Not (Top padding greater than 0 if iPhoneX)

if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    CGFloat topPadding = window.safeAreaInsets.top;
    self.headerViewHeight.constant = (topPadding>0) ? 46+topPadding : 60;
 }
user6788419
  • 7,196
  • 1
  • 16
  • 28
  • I did something like this and It worked but I don't know If It is a best approach :) – Mr Some Dev. Nov 29 '17 at 08:10
  • yeah I am also thinking the same. Please do some research – user6788419 Nov 29 '17 at 08:16
  • Note: Can't call this in viewDidLoad of your main ViewController, as UIWindow won't be accessible until after at least one run loop. To bypass you can simply move your viewDidLoad code into a new method `postViewDidLoad` and use `[self performSelector:@selector(postViewDidLoad) afterDelay:0.0f];` in the original viewDidLoad method, then UIWindow will be accessible and this will work. – Albert Renshaw Jun 23 '18 at 01:35
3

Use this(swift 3):

constraint_heightTopBar.constant = UIApplication.shared.statusBarFrame.maxY + 44

It gives you a standard height 64 for all other devices and 88 for iPhoneX.You can adjust the value '44' as per your need.
Remember that status bar height is 20 for other devices and 44 for PhoneX.So you just need to set the view height as per your need.Rest is done.
It will work on all iOS versions and for all devices :-)

For objC, use CGRectGetMaxY(frame).

Reckoner
  • 1,041
  • 2
  • 13
  • 29
1

If you're using >= iOS 13, then

CGFloat safeAreaGap = 0;
UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
if (window != nil) {
    safeAreaGap = window.safeAreaInsets.bottom; // for bottom
    safeAreaGap = window.safeAreaInsets.top; // for top
}

Or

if let window = UIApplication.shared.windows.first {
    self.safeAreaInsetsBottom = window.safeAreaInsets.bottom
}
Mahmud Ahsan
  • 1,755
  • 19
  • 18