2017-09-15 74 views
13

我的问题的答案暗示在this question,所以我认为答案是禁用我的UIToolbar视图的自动布局。iOS 11 UIBarButtonItem images not size

,据称为视图的工作代码

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%,以确保我正在查看正确的代码,并且它的行为与我预期的相同。

correct version

这里是他们的样子在模拟器的Xcode 9.0 GM和iOS 11.注意按钮的顶行调整正确,但下面一行扩展以填充分配给标签栏的空间。在iPad上以及各种设备上也会发生同样的行为。

iOS 11

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

回答

42

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 
} 

目标C

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

感谢您的提示。我添加了Obj C版本。 – JScarry

+0

太棒了!它为我工作。 thankx。 – Bucket

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!) 

的2线对锚宽/高从Fallstreak的答案来了,是在这种情况下的解决方案。