iOS 11 iPhone X simulator UITabBar icons and title

2019-01-10 03:13发布

问题:

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 8

回答1:

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.



回答2:

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


回答3:

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.



回答4:

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
    }
}


回答5:

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.



回答6:

I had the same problem.

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

It starts working as expected...

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



回答7:

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
    }
}


回答8:

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

  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

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. ¯_(ツ)_/¯


回答9:

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()


回答10:

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];
}];


回答11:

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/



回答12:

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.



回答13:

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);
}


回答14:

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.



回答15:

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.



回答16:

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



回答17:

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



回答18:

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

Faced the same problem and removing this solved the issue.



回答19:

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



回答20:

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.



回答21:

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



回答22:

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



回答23:

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)
    }


回答24:

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.



回答25:

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)


回答26:

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.


回答27:

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;
    }
} 


回答28:

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.



回答29:

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).