UIBarButtonItems not showing

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.



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;



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.

Replies

Strange. Seems to be working for me even without the constraints. I tried your code from within viewDidLoad.


Where are you doing this in your code? Do you have a valid self.navigationItem when you do this? Are you doing this from within a block? Then maybe you need to make sure it's on the main thread.

Yes, everything is valid, called from viewDidLoad. 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
    }