2017-09-15 57 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的答案來了,是在這種情況下的解決方案。

相關問題