137

Anyone having issue with the iPhone X simulator around the UITabBar component?

Mine seem to be rendering the icons and title on top of each other, I'm not sure if I'm missing anything, I also ran it in the iPhone 8 simulator, and one actual devices where it looks fine just as shown on the story board.

iPhone X:

iPhone X UITabBar bug

iPhone 8

iPhone 8 UITabBar works

adrian chen
  • 1,518
  • 2
  • 7
  • 9

32 Answers32

41

I was able to get around the problem by simply calling invalidateIntrinsicContentSize on the UITabBar in viewDidLayoutSubviews.

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self.tabBar invalidateIntrinsicContentSize];
}

Note: The bottom of the tab bar will need to be contained to the bottom of the main view, rather than the safe area, and the tab bar should have no height constraint.

Grzegorz Krukowski
  • 14,128
  • 5
  • 41
  • 61
David Hooper
  • 543
  • 3
  • 4
  • I've got a tab bar with no height constraint, constrained to the Bottom Layout Guide, and this did not work for me. Any other ideas? – Kenny Wyland Nov 05 '17 at 19:49
  • 1
    Not working when homeVC present VC A, then dismiss A, and push VC B from homeVC. This is a workaround https://stackoverflow.com/a/47225653/1553324 – ooops Nov 13 '17 at 16:31
  • 1
    Adding this method combined with pinning the tab bar to the bottom of its superview (_not_ the safe area) worked for me. – Drew C Nov 29 '17 at 20:32
  • 3
    I also needed to add `[self.view layoutIfNeeded]`. – Iulian Onofrei Dec 03 '17 at 21:17
  • Hello I have programmatically created tab bar controller and shows on successful login in a home screen in that where do I need to write this code which you have suggested – Siddh Dec 11 '17 at 09:41
  • This worked for iOS 11.0 but it is not working for iOS 11.1 and iOS 11.2 – Ashish Verma Dec 18 '17 at 12:16
  • 1
    This works but I learned I must also pay attention to the sizes of the _images_ in the tab bar buttons. In landscape mode (on compact devices, but not iPad and iPhone Plus models), the system uses a compact tab bar which is supposed to have smaller images that you can set with the `landscapeImage` property of the tab bar button. Recommended sizes are in [Apple HIG's] (https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/) under _Custom Icon Size_ – RobP Jun 29 '18 at 16:12
  • @ooops https://stackoverflow.com/a/50233139/1147209 I think this will simply fix the problem. – Weizhi Oct 09 '18 at 07:21
  • This is also better than subclassing because subclassing UITabBar breaks automatic dark mode support – VoidLess Aug 05 '19 at 10:07
26

Answer provided by VoidLess fixes TabBar problems only partially. It fixes layout problems within the tabbar, but if you use viewcontroller that hides the tabbar, the tabbar is rendered incorrectly during animations (to reproduce it is best 2 have 2 segues - one modal and one push. If you alternate the segues, you can see the tabbar being rendered out of place). The code bellow fixes both problems. Good job apple.

class SafeAreaFixTabBar: UITabBar {

var oldSafeAreaInsets = UIEdgeInsets.zero

@available(iOS 11.0, *)
override func safeAreaInsetsDidChange() {
    super.safeAreaInsetsDidChange()

    if oldSafeAreaInsets != safeAreaInsets {
        oldSafeAreaInsets = safeAreaInsets

        invalidateIntrinsicContentSize()
        superview?.setNeedsLayout()
        superview?.layoutSubviews()
    }
}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    var size = super.sizeThatFits(size)
    if #available(iOS 11.0, *) {
        let bottomInset = safeAreaInsets.bottom
        if bottomInset > 0 && size.height < 50 && (size.height + bottomInset < 90) {
            size.height += bottomInset
        }
    }
    return size
}

override var frame: CGRect {
    get {
        return super.frame
    }
    set {
        var tmp = newValue
        if let superview = superview, tmp.maxY != 
        superview.frame.height {
            tmp.origin.y = superview.frame.height - tmp.height
        }

        super.frame = tmp
        }
    }
}

Objective-C code:

@implementation VSTabBarFix {
    UIEdgeInsets oldSafeAreaInsets;
}


- (void)awakeFromNib {
    [super awakeFromNib];

    oldSafeAreaInsets = UIEdgeInsetsZero;
}


- (void)safeAreaInsetsDidChange {
    [super safeAreaInsetsDidChange];

    if (!UIEdgeInsetsEqualToEdgeInsets(oldSafeAreaInsets, self.safeAreaInsets)) {
        [self invalidateIntrinsicContentSize];

        if (self.superview) {
            [self.superview setNeedsLayout];
            [self.superview layoutSubviews];
        }
    }
}

- (CGSize)sizeThatFits:(CGSize)size {
    size = [super sizeThatFits:size];

    if (@available(iOS 11.0, *)) {
        float bottomInset = self.safeAreaInsets.bottom;
        if (bottomInset > 0 && size.height < 50 && (size.height + bottomInset < 90)) {
            size.height += bottomInset;
        }
    }

    return size;
}


- (void)setFrame:(CGRect)frame {
    if (self.superview) {
        if (frame.origin.y + frame.size.height != self.superview.frame.size.height) {
            frame.origin.y = self.superview.frame.size.height - frame.size.height;
        }
    }
    [super setFrame:frame];
}


@end
Leon
  • 390
  • 1
  • 13
Raimundas Sakalauskas
  • 1,625
  • 18
  • 22
22

There is a trick by which we can solve the problem.

Just put your UITabBar inside a UIView.

This is really working for me.

Or you can follow this Link for more details.

Avineet Gupta
  • 576
  • 9
  • 21
19

override UITabBar sizeThatFits(_) for safeArea

extension UITabBar {
    static let height: CGFloat = 49.0

    override open func sizeThatFits(_ size: CGSize) -> CGSize {
        guard let window = UIApplication.shared.keyWindow else {
            return super.sizeThatFits(size)
        }
        var sizeThatFits = super.sizeThatFits(size)
        if #available(iOS 11.0, *) {
            sizeThatFits.height = UITabBar.height + window.safeAreaInsets.bottom
        } else {
            sizeThatFits.height = UITabBar.height
        }
        return sizeThatFits
    }
}
Hexfire
  • 5,324
  • 8
  • 28
  • 40
Cruz
  • 2,436
  • 16
  • 26
  • Brilliant. I have just set custom size of my tabbar and wondering why it doesn't work on iPhoneX. Other solutions doesn't work for me as I am using Tab Bar Controller and it doesn't include constraints. – Jindřich Rohlík Sep 25 '18 at 13:24
  • 1
    Looks like this technique broke with Xcode 12 / iOS 14. – picciano Sep 17 '20 at 23:04
13

I added this to viewWillAppear of my custom UITabBarController, because none of the provided answers worked for me:

tabBar.invalidateIntrinsicContentSize()
tabBar.superview?.setNeedsLayout()
tabBar.superview?.layoutSubviews()
IKavanagh
  • 5,704
  • 11
  • 38
  • 44
aaannjjaa
  • 238
  • 3
  • 6
10

I had the same problem.

enter image description here

If I set any non-zero constant on the UITabBar's bottom constraint to the safe area:

enter image description here

It starts working as expected...

enter image description here

That is the only change I made and I have no idea why it works but if anyone does I'd love to know.

moliveira
  • 764
  • 8
  • 16
  • 1
    This was what i did at the end to get it working, but yeah I have no idea why or understand what it's doing. To me it still feels like a bug – adrian chen Dec 18 '17 at 08:52
7

Moving the tab bar 1 point away from the bottom worked for me.

Of course you'll get a gap by doing so which you'll have to fill in some way, but the text/icons are now properly positioned.

deej
  • 1,568
  • 1
  • 25
  • 25
7

Aha! It's actually magic!

I finally figured this out after hours of cursing Apple.

UIKit actually does handle this for you, and it appears that the shifted tab bar items are due to incorrect setup (and probably an actual UIKit bug). There is no need for subclassing or a background view.

UITabBar will "just work" if it is constrained to the superview's bottom, NOT to the bottom safe area.

It even works in Interface builder.

Correct Setup

Working in IB

  1. In interface builder, viewing as iPhone X, drag a UITabBar out to where it snaps to the bottom safe area inset. When you drop it, it should look correct (fill the space all the way to the bottom edge).
  2. You can then do an "Add Missing Constraints" and IB will add the correct constraints and your tab bar will magically work on all iPhones! (Note that the bottom constraint looks like it has a constant value equal to the height of the iPhone X unsafe area, but the constant is actually 0)

Sometimes it still doesn't work

Broken in IB

What's really dumb is that you can actaully see the bug in IB as well, even if you add the exact constraints that IB adds in the steps above!

  1. Drag out a UITabBar and don't snap it to the bottom safe area inset
  2. Add leading, trailing and bottom constraints all to superview (not safe area) Weirdly, this will fix itself if you do a "Reverse First And Second Item" in the constraint inspector for the bottom constraint. ¯_(ツ)_/¯
RyanM
  • 4,194
  • 4
  • 34
  • 43
6

Fixed by using subclassed UITabBar to apply safeAreaInsets:

class SafeAreaFixTabBar: UITabBar {

    var oldSafeAreaInsets = UIEdgeInsets.zero

    @available(iOS 11.0, *)
    override func safeAreaInsetsDidChange() {
        super.safeAreaInsetsDidChange()

        if oldSafeAreaInsets != safeAreaInsets {
            oldSafeAreaInsets = safeAreaInsets

            invalidateIntrinsicContentSize()
            superview?.setNeedsLayout()
            superview?.layoutSubviews()
        }
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        if #available(iOS 11.0, *) {
            let bottomInset = safeAreaInsets.bottom
            if bottomInset > 0 && size.height < 50 {
                size.height += bottomInset
            }
        }
        return size
    }
}
VoidLess
  • 1,165
  • 7
  • 7
  • Solves part of the problems, but not all. Please see the full answer bellow – Raimundas Sakalauskas Nov 10 '17 at 14:52
  • It worked for me when I try to present VCA, then dismiss VCA, push VCB. – Tai Le Mar 16 '18 at 08:13
  • This works for me but I need to put the bottom constraint to the superview and not the safe area. – yajra Aug 28 '18 at 09:24
  • What do I do with this new class after I create it? I tried looking through my application for any occurrence of UITabBar and replace them with the SafeAreaFixTabBar... I found these occurrences: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { SafeAreaFixTabBar.appearance().barTintColor = ... SafeAreaFixTabBar.appearance().backgroundColor = ... SafeAreaFixTabBar.appearance().tintColor = ... But didn't fix anything – user1019042 May 12 '19 at 13:11
4

Solved for me by calling [tabController.view setNeedsLayout]; after dismissing the modal in completion block.

[vc dismissViewControllerAnimated:YES completion:^(){ 
     UITabBarController* tabController = [UIApplication sharedApplication].delegate.window.rootViewController;
     [tabController.view setNeedsLayout];
}];
yogevbd
  • 1,200
  • 10
  • 18
2

The UITabBar is increasing in height to be above the home button/line, but drawing the subview in its original location and overlaying the UITabBarItem over the subview.

As a workaround you can detect the iPhone X and then shrink the height of the view by 32px to ensure the tab bar is displayed in the safe area above the home line.

For example, if you're creating your TabBar programatically replace

self.tabBarController = [[UITabBarController alloc] init];
self.window.rootViewController = self.tabBarController;

With this:

#define IS_IPHONEX (([[UIScreen mainScreen] bounds].size.height-812)?NO:YES)
self.tabBarController = [[UITabBarController alloc] init];    
self.window.rootViewController = [[UIViewController alloc] init] ;
if(IS_IPHONEX)
    self.window.rootViewController.view.frame = CGRectMake(self.window.rootViewController.view.frame.origin.x, self.window.rootViewController.view.frame.origin.y, self.window.rootViewController.view.frame.size.width, self.window.rootViewController.view.frame.size.height + 32) ;
[self.window.rootViewController.view addSubview:self.tabBarController.view];
self.tabBarController.tabBar.barTintColor = [UIColor colorWithWhite:0.98 alpha:1.0] ;
self.window.rootViewController.view.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1.0] ;

NOTE: This could well be a bug, as the view sizes and tab bar layout are set by the OS. It should probably display as per Apple's screenshot in the iPhone X Human Interface Guidelines here: https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/

A.Badger
  • 4,039
  • 1
  • 22
  • 18
  • 1
    i see, I didn't create the Tab bar programatically, i used the storyboard to build it with constraints set to be the bottom of the screen. It does feel odd to me that we have to detect if it's an iPhone X then go do some rejigging on the layout, while they just bump up the height of the TabBar by it self without any code changes. – adrian chen Sep 14 '17 at 10:02
  • This feels more like a bug to me now, I think i'm going to do a bug report on this and see what comes out of it. Thanks for your help!! – adrian chen Sep 14 '17 at 14:39
  • It's really not a great idea to use the exact height of the main screen bounds to determine if the app is running on iPhone X. What happens if next year's model is the same point size? Or if the app is running in landscape mode? – roperklacks Sep 15 '17 at 15:56
  • Transparency doesn't seem to affect my icons being set improperly. They're messed up whether the UITabBar is opaque or transparent. – Adama Sep 16 '17 at 23:37
  • It would appear you are actually adding 32px to the height of the frame rather than subtracting from it? – Perry Oct 04 '17 at 21:55
2

My case was that I had set a custom UITabBar height in my UITabBarController, like this:

  override func viewWillLayoutSubviews() {            
        var tabFrame = tabBar.frame
        tabFrame.size.height = 60
        tabFrame.origin.y = self.view.frame.size.height - 60
        tabBar.frame = tabFrame
    }

Removing this code was the solution for the TabBar to display correctly on iPhone X.

Gytis
  • 670
  • 6
  • 18
2

The simplest solution I found was to simply add a 0.2 pt space between the bottom of the tab bar and the bottom of the safeAreaLayoutGuide.bottomAnchor like so.

tabBar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -0.2)
1

I was having the same issue when I was trying to set the frame of UITabBar in my custom TabBarController.

self.tabBar.frame = CGRectMake(0, self.view.frame.size.height - kTabBarHeight, self.view.frame.size.width, kTabBarHeight);

When I just adjusted it to the new size the issue went away

if(IS_IPHONE_X){
    self.tabBar.frame = CGRectMake(0, self.view.frame.size.height - kPhoneXTabBarHeight, self.view.frame.size.width, kPhoneXTabBarHeight);
}
else{
    self.tabBar.frame = CGRectMake(0, self.view.frame.size.height - kTabBarHeight, self.view.frame.size.width, kTabBarHeight);
}
Evgeny
  • 140
  • 1
  • 7
  • 1
    What are the values of `kPhoneXTabBarHeight `? – Tiago Veloso Sep 21 '17 at 16:47
  • I just added 32 points to the previous value of kTabBarHeight (which was 45). But you don't have to specify exactly the same value, for me it's also works fine without specifying the frame for the tabBar. But if you do specify it, you have to adjust for additional height on iPhone X. – Evgeny Sep 27 '17 at 21:24
  • 1
    Total hack, but it was the only one of these solutions that got it looking right for me. – Kenny Wyland Nov 05 '17 at 20:03
  • When you're having a custom view as your tabbar you like to use this hack to make your custom view fit for iPhone X. – Hemang Nov 07 '17 at 11:24
  • @Evgeny, I guess, the previous value was 49 and not 45. – Hemang Nov 07 '17 at 11:26
  • 1
    @Hemang no, it was 45 for this project I borrowed this code from. – Evgeny Nov 08 '17 at 11:46
1

I encountered this today with a a UITabBar manually added to the view controller in the storyboard, when aligning to the bottom of the safe area with a constant of 0 I would get the issue but changing it to 1 would fix the problem. Having the UITabBar up 1 pixel more than normal was acceptable for my application.

Alan MacGregor
  • 491
  • 2
  • 13
1

I have scratched my head over this problem. It seems to be associated with how the tabBar is initialized and added to view hierarchy. I also tried above solutions like calling invalidateIntrinsicContentSize, setting the frame, and also bottomInsets inside a UITabBar subclass. They seem to work however temporarily and they break of some other scenario or regress the tab bar by causing some ambiguous layout issue. When I was debugging the issue I tried assigning the height constraints to the UITabBar and centerYAnchor, however neither fixed the problem. I realized in view debugger that the tabBar height was correct before and after the problem reproduced, which led me to think that the problem was in the subviews. I used the below code to successfully fix this problem without regressing any other scenario.

- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if (DEVICE_IS_IPHONEX())
    {
        [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            for (UIView *view in self.tabBar.subviews)
            {
                if ([NSStringFromClass(view.class) containsString:@"UITabBarButton"])
                {
                    if (@available (iOS 11, *))
                    {
                        [view.bottomAnchor constraintEqualToAnchor:view.superview.safeAreaLayoutGuide.bottomAnchor].active = YES;
                    }
                }
            }
        } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            [self.tabBar layoutSubviews];
        }];
    }
}

Assumptions: I am doing this only for iPhone X, since it doesn't seem to reproduce on any other device at the moment. Is based on the assumption that Apple doesn't change the name of the UITabBarButton class in future iOS releases. We're doing this on UITabBarButton only when means if apple adds more internal subviews in to UITabBar we might need to modify the code to adjust for that.

Please lemme know if this works, will be open to suggestions and improvements!

It should be simple to create a swift equivalent for this.

Rushabh
  • 611
  • 5
  • 15
1

From this tutorial:

https://github.com/eggswift/ESTabBarController

and after initialization of tab bar writing this line in appdelegate class

(self.tabBarController.tabBar as? ESTabBar)?.itemCustomPositioning = .fillIncludeSeparator

Solves my problem of tab bar.

Hope its solves your problem

Thanks

Siddh
  • 712
  • 4
  • 21
1

Select tabbar and set "Save Area Relative Margins" checkbox in Inspector Editor like this:

enter image description here

AnnGoro
  • 46
  • 1
1

I had the similar problem, at first it was rendered correctly but after setting up badgeValue on one of the tabBarItem it broke the layout. What it worked for me without subclassing UITabBar was this, on my already created UITabBarController subclass.

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSLayoutYAxisAnchor *tabBarBottomAnchor = self.tabBar.bottomAnchor;
    NSLayoutYAxisAnchor *tabBarSuperviewBottomAnchor = self.tabBar.superview.bottomAnchor;
    [tabBarBottomAnchor constraintEqualToAnchor:tabBarSuperviewBottomAnchor].active = YES;
    [self.view layoutIfNeeded];
}

I used tabBar superview to make sure that the constraints/anchors are on the same view hierarchy and avoid crashes.

Based on my understanding, since this seems to be a UIKit bug, we just need to rewrite/re-set the tab bar constraints so the auto layout engine can layout the tab bar again correctly.

rgkobashi
  • 2,057
  • 12
  • 22
0

If you have any height constraint for the Tab Bar try removing it .

Faced the same problem and removing this solved the issue.

rustylepord
  • 5,331
  • 6
  • 34
  • 46
0

I created new UITabBarController in my storyboard and pushed all view controllers to this new UITabBarConttoller. So, all work well in iPhone X simulator.

  • This also fixed it for me. There's something different about the way Xcode 9 IB generates the UITabBarController's XML that fixed the issue. – Tiago Nov 27 '17 at 17:08
0

For iPhone you can do this, Subclass UITabBarController.

class MyTabBarController: UITabBarController {

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if #available(iOS 11, *) {
        self.tabBar.heightAnchor.constraint(equalToConstant: 40).isActive = true
        self.tabBar.invalidateIntrinsicContentSize()
    }
  }
}

Goto Storyboard and allow Use Safe Area Layout Guide and change class of UITabbarController to MyTabBarController

P.S This solution is not tested in case of universal application and iPad.

NaXir
  • 2,193
  • 2
  • 22
  • 31
0

try to change splash screen with @3x size is (3726 × 6624)

Sob7y
  • 17
  • 5
0

For me, remove [self.tabBar setBackgroundImage:] work, maybe it's UIKit bug

KelaKing
  • 86
  • 6
0

For me this fixed all the issues:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let currentHeight = tabBar.frame.height
        tabBar.frame = CGRect(x: 0, y: view.frame.size.height - currentHeight, width: view.frame.size.width, height: currentHeight)
    }
Durdu
  • 3,627
  • 1
  • 20
  • 38
0

I was using a UITabBarController in the storyboard and at first it was working alright for me, but after upgrading to newer Xcode version it started giving me issues related to the height of the tabBar.

For me, the fix was to delete the existing UITabBarController from storyboard and re-create by dragging it from the interface builder objects library.

enigma
  • 829
  • 8
  • 20
0

For those who write whole UITabBarController programmatically, you can use UITabBarItem.appearance().titlePositionAdjustment to adjust the title position

So in this case that you want add a gap between Icon and Title use it in viewDidLoad:

    override func viewDidLoad() {
        super.viewDidLoad()

        // Specify amount to offset a position, positive for right or down, negative for left or up
        let verticalUIOffset = UIOffset(horizontal: 0, vertical: hasTopNotch() ? 5 : 0)

        UITabBarItem.appearance().titlePositionAdjustment = verticalUIOffset
    }

detecting if device has Notch screen:

  func hasTopNotch() -> Bool {
      if #available(iOS 11.0, tvOS 11.0, *) {
        return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
      }
      return false
  }
Saeid
  • 1,962
  • 3
  • 25
  • 51
0

For me the solution was to select the Tab Bar in the view hierarchy, then go to: Editor -> Resolve Auto Layout Issues, and under "Selected Views" (not "All views in view") choose "Add missing constraints".

syonip
  • 1,930
  • 20
  • 22
-1

I was having the same issue which was solved by setting the items of the tabBar after the tab bar was laid out.

In my case the issue happened when:

  1. There is a custom view controller
  2. A UITabBar is created in the initializer of the view controller
  3. The tab bar items are set before view did load
  4. In view did load the tab bar is added to the main view of the view controller
  5. Then, the items are rendered as you mention.
Barbara R
  • 1,030
  • 5
  • 17
-1

I think this is a bug UIKit from iPhoneX. because it works:

if (@available(iOS 11.0, *)) {
    if ([UIApplication sharedApplication].keyWindow.safeAreaInsets.top > 0.0) {
       self.tabBarBottomLayoutConstraint.constant = 1.0;
    }
} 
RomanV
  • 419
  • 4
  • 5
-1

I believe you might be laying out the tab bar against the bottom safe layout guide. This is probably not what you want since the tab bar does seems to do its own calculations to position the tab bar items safely on top of the home line in the iPhone X. Setup your bottom constraint against the superview bottom. You should see that it lays out correctly on iPhone X as well as other iPhones.

-1

I ran into this bug on my launch screen storyboard, which can't be customised via subclassing. After some analysis I managed to figure out the cause - I was using a UITabBar directly. Switching to a UITabBarController, which encapsulates a UITabBar, solved the issue.

Note - it is possible that this will be fixed by iOS 11.1, so may not effect real iPhone X apps (since it is likely that the iPhone X will be released running iOS 11.1).

Jordan Smith
  • 10,122
  • 7
  • 63
  • 111