我正在测试一个简单的 UIToolbar
, 有两个 UIBarButtonItem
作为项目,一个使用 initWithCustomView:
构建方法,另一种使用initWithTitle:style:target:action:
方法。
第二个按钮可以在工具栏上查看,但第一个按钮不见了。
该问题仅在 iOS 9 和 iOS 10 上出现。在 iOS 11 上不会出现。
有谁有想法吗?
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 }]];
最佳答案
您需要调用sizeToFit
您的 UIButton
上的方法在将其添加到工具栏之前。
像这样的东西:[button sizeToFit]; // (Objective-C)
或者button.sizeToFit() // (Swift)
虽然回答这个问题为时已晚,但希望这对您或其他人有所帮助。
关于ios9 - UIToolbar 不显示带有自定义 View 的 UIBarButtonItem(仅在 iOS 11 以下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796609/