UIBarButtonItem not working in ios11

1.3k views Asked by At

Long story short iOS10 left, right buttons, custom label working without issues, iOS11 none of the showing. I've read elsewhere that I need to add constraints for the buttons but that is not helping. Code called in viewDidLoad().

self.connectionButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0,0.0,74.0,29.0)];
[self.connectionButton.widthAnchor constraintEqualToConstant:74].active = YES;
[self.connectionButton.heightAnchor constraintEqualToConstant:29].active = YES;
self.connectionButton.backgroundColor = [UIColor yellowColor];
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:self.connectionButton];
self.navigationItem.rightBarButtonItem = buttonItem;

Appearance:

[[UINavigationBar appearance] setTranslucent:YES];
[[UINavigationBar appearance] setShadowImage:[UIImage new]];
[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor clearColor]];

When I check the frame during run time it's correct (0,0,74,29). No button is shown in the bar though.

XCode 9 beta 8, not working on either device nor simulator.

1

There are 1 answers

0
Tom On

With more testing I found out that the navigation bar doesn't show anything - not even the title in default appearance. After hours wasted on commenting/uncommenting pieces of unrelated code I found the culprit:

    override var traitCollection: UITraitCollection {  
        var horizTraitCollection = UITraitCollection(horizontalSizeClass: .regular)  
        if view.bounds.width < view.bounds.height {  
            horizTraitCollection = UITraitCollection(horizontalSizeClass: .compact)  
        }

        return UITraitCollection(traitsFrom: [horizTraitCollection, UITraitCollection(verticalSizeClass: super.traitCollection.verticalSizeClass)])
     }

This is what I use override size class for portrait/landscape presentation. IMO completely unrelated to navigation bar appearance. No idea why is it breaking the navigation bar or how to fix it .

EDIT: After some tweaking I was able to get it working on iPads but not iPhones. After some more tweaking I got it working on iPhone as well:

override var traitCollection: UITraitCollection {  
    if UIDevice.current.userInterfaceIdiom == .pad {  
        var horizTraitCollection = UITraitCollection(horizontalSizeClass: .regular)  
        if UIDevice.current.orientation.isPortrait {  
            horizTraitCollection = UITraitCollection(horizontalSizeClass: .compact)  
        }  
        return UITraitCollection(traitsFrom: [horizTraitCollection, UITraitCollection(verticalSizeClass: super.traitCollection.verticalSizeClass)])  
    }  
    return super.traitCollection  
}