iOS 11 个 UIBarButtonItem 图像未调整大小

iOS 11 UIBarButtonItem images not sizing

我的问题的答案已在 中暗示,所以我认为答案是为我的 UIToolbar 视图禁用自动布局。

据说适用于视图的代码是

cButton.translatesAutoresizingMaskIntoConstraints = YES;

但我不确定它是否适用于我的代码,因为 UIToolbar 没有继承自 UIView。

我在游戏中使用了很多小图像,这些图像的大小因设备和方向而异。与其拥有大量不同的图像,并在 Apple 推出新设备时添加新图像,我决定为每个图像制作一张 160x160 图像,然后在使用时调整其大小。这在 iOS 4 - iOS 10 中运行良好,但在 iOS 11 中失败。

代码非常简单:

// Get the image
NSString *pictFile = [[NSBundle mainBundle] pathForResource:@"Correct" ofType:@"png"];
UIImage *imageToDisplay = [UIImage imageWithContentsOfFile:pictFile];
UIImage *cImage  = [UIImage imageWithCGImage:imageToDisplay.CGImage scale:[UIScreen mainScreen].scale orientation:imageToDisplay.imageOrientation];

UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cButton setImage:cImage forState:UIControlStateNormal];
[cButton setTitle:@"c" forState:UIControlStateNormal];

//set the frame of the button to the size of the image
cButton.frame = CGRectMake(0, 0, standardButtonSize.width, standardButtonSize.height);

//create a UIBarButtonItem with the button as a custom view
c = [[UIBarButtonItem alloc] initWithCustomView:cButton];

这是 pre11 的样子。栏按钮项目已调整大小并很好地适合底部栏。请注意,我将复选标记的大小减小了 50%,只是为了确保我看到的是正确的代码,并且它的行为符合我的预期。

这是它们在 Xcode 9.0 GM 和 iOS 11 的模拟器中的样子。请注意,顶行按钮正确调整大小,但底行扩展以填充 space 分配给标签栏。同样的行为也发生在 iPad 和各种设备上。

关于如何禁用自动布局或添加约束的任何想法?

BarButtonItem (iOS11\xCode9) 使用自动布局而不是框架。试试这个 (Swift):

if #available(iOS 9.0, *) {
    cButton.widthAnchor.constraint(equalToConstant: customViewButton.width).isActive = true
    cButton.heightAnchor.constraint(equalToConstant: customViewButton.height).isActive = true
}

Objective C

if (@available(iOS 9, *)) {
     [cButton.widthAnchor constraintEqualToConstant: standardButtonSize.width].active = YES;
     [cButton.heightAnchor constraintEqualToConstant: standardButtonSize.height].active = YES;
}

Fallstreak answer (+1) 是我的解决方案。我有一个自定义视图无法使用。只是想分享我必须做些什么才能使导航项中的自定义视图起作用。这就是全部 swift 3

let backButtonView = BackButtonView.loadNib()
backButtonView?.addTarget(self, action: #selector(returnToPrevious), for: .touchUpInside)
backButtonView.widthAnchor.constraint(equalToConstant: backButtonView.frame.width).isActive = true
backButtonView.heightAnchor.constraint(equalToConstant: backButtonView.frame.height).isActive = true
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButtonView!)

关于锚 width/height 的 2 行来自 Fallstreak 的回答,是这种情况下的解决方案。