ios9 - UIToolbar 不显示带有自定义 View 的 UIBarButtonItem(仅在 iOS 11 以下)

标签 ios9 ios10 uibarbuttonitem uitoolbar custom-view

我正在测试一个简单的 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 }]];

screenshot from iPad 2

最佳答案

您需要调用sizeToFit您的 UIButton 上的方法在将其添加到工具栏之前。

像这样的东西:[button sizeToFit]; // (Objective-C)或者button.sizeToFit() // (Swift)
虽然回答这个问题为时已晚,但希望这对您或其他人有所帮助。

关于ios9 - UIToolbar 不显示带有自定义 View 的 UIBarButtonItem(仅在 iOS 11 以下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796609/

相关文章:

ios - 使用 GCD 在 HTML 文件中写入日志无法按预期工作

apple-push-notifications - ios10 自定义推送通知声音未播放

ios - UIBarButton 未显示在 UINavigationBar 中

swift - iOS10 swift 2.2 在 Instagram 上分享 openURL& canOpenURL 更改

ios9 - 在 SFSafariViewController 关闭时,禁用状态栏隐藏动画 [iOS 9]

iOS9 此应用程序正在从后台线程修改自动布局引擎,这可能导致引擎损坏和奇怪的崩溃

ios - 通过在 iOS10+ 上打开本地通知来检测应用是否已启动

ios - map 扩展是否可供开发者使用

ios - 如何为纯文本实现在应用程序中打开

ios - 如何格式化右边的两个UIBarButtonItems彼此相邻?