簡體   English   中英

UIButton initWithFrame:CGRectMake在Xcode 9.3中不起作用

[英]UIButton initWithFrame:CGRectMake not working in Xcode 9.3

將xcode更新為9.3,我在使用可編程按鈕時遇到問題

在Xcode 8中,我可以通過以下方式獲得它,並且效果很好

UIButton *btnSettingsButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[btnSettingsButton setBackgroundImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[btnSettingsButton addTarget:self action:@selector(setttingsDashboard:) forControlEvents:UIControlEventTouchUpInside];
[btnSettingsButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *btnSettingsItem =[[UIBarButtonItem alloc] initWithCustomView:btnSettingsButton];

屏幕Xcode 8 在此處輸入圖像描述

按鈕的圖片“ settings.png”以25的高度和25的寬度很好地顯示了我。

但是當我使用xcode 9時,不要使用initWithFrame:CGRectMake,它會變得更大。 “按鈕圖片的大小

屏幕Xcode 9.3 在此處輸入圖像描述

我怎樣才能解決這個問題?

您可以將圖片大小調整為25x25

要么

只需為圖片設置內容模式

[[btnSettingsButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
[btnSettingsButton setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];

在添加條形按鈕項時是否存在問題:-

UIBarButtonItem *settingsButton=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"settings.png"] style:UIBarButtonItemStyleDone target:self action:@selector(setttingsDashboard:)];

通過放置解決

[btnSettingsButton setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
btnSettingsButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
btnSettingsButton.contentEdgeInsets = UIEdgeInsetsMake(10, 0, 10, -20); 

調用initWithCustomView ,您正在制作一個自定義欄按鈕項。

  • 在iOS 10及更低版本中,它的大小是固定的(如您所正確看到的,基於frame )。

  • 但是在iOS 11中,此行為完全改變了:iOS 11使用自動布局來獲取自定義欄按鈕項目的大小。

因此,您需要提供內部自動布局約束 (例如,高度和寬度約束),這些約束決定了自定義視圖的大小。 如果將按鈕的高度限制設置為25,寬度限制設置為25,那么一切都會很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM