Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIToolbar doesn't show UIBarButtonItem with custom view (only below iOS 11)

I'm testing a simple UIToolbar, with two UIBarButtonItem as items, one built using initWithCustomView: method, the other one using initWithTitle:style:target:action: method.

The second button cand be viewed on the toolbar, but the first one is missing.

The problem occurs only on iOS 9 and iOS 10. It doesn't occur on iOS 11.

Does anyone have any idea?

UIToolbar *toolbar = [[UIToolbar alloc] init];
[toolbar setTranslatesAutoresizingMaskIntoConstraints:NO];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"one" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:audioOnIcon] forState:UIControlStateNormal];

[toolbar setItems:[NSArray arrayWithObjects:
                   [[UIBarButtonItem alloc] initWithCustomView:button],
                   [[UIBarButtonItem alloc] initWithTitle:@"title" style:UIBarButtonItemStylePlain target:self action:nil],
                   nil]];

[toolbar setBackgroundImage:[UIImage new] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[toolbar setShadowImage:[UIImage new] forToolbarPosition:UIBarPositionAny];
toolbar.accessibilityIdentifier = toolbarIdentifier;

[self.view insertSubview:toolbar atIndex:[self getSubviewIndex:toolbar.accessibilityIdentifier]];

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[subview]-0-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:@{ @"subview": toolbar}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[subview]-padding-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:@{ @"padding": @(2 * PADDING) } views:@{ @"subview": toolbar }]];

screenshot from iPad 2

like image 392
Denis Visan Avatar asked Oct 17 '17 18:10

Denis Visan


1 Answers

You need to call the sizeToFit method on your UIButton before adding it to toolbar.

Something like this:
[button sizeToFit]; // (Objective-C)
OR
button.sizeToFit() // (Swift)

Although its to late to answer to this question, but hope this helps you or someone else.

like image 187
S1LENT WARRIOR Avatar answered Oct 24 '22 11:10

S1LENT WARRIOR