iOS 11 UIBarButtonItem 图片尺寸不正确

14
我的问题的答案在这个问题中得到了暗示,因此我认为答案是禁用我的UIToolbar视图的自动布局。

被认为对视图有效的代码是

cButton.translatesAutoresizingMaskIntoConstraints = YES;

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

我在游戏中使用了许多小图像,这些图像的大小因设备和方向而异。为了避免有很多不同大小的图像,并在苹果推出新设备时添加新图像,我决定制作一个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];

这是前11版本的外观。工具栏按钮已调整大小并适合底部栏。请注意,我将选中标记的大小减小了50%,只是为了确保我正在查看正确的代码,并且它的行为与我的预期相符。

correct version

这是Xcode 9.0 GM和iOS 11模拟器中的外观。请注意,顶部按钮行会正确调整大小,但底部行会扩展以填充分配给选项卡栏的空间。在iPad和其他设备上也会出现相同的行为。

iOS 11

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

2个回答

49

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;
}

感谢你的提示。我已经添加了Obj C版本。 - JScarry

0

Fallstreak的回答(+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!)

关于锚点宽度/高度的两行代码来自Fallstreak的答案,并且在这种情况下是解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接