简体   繁体   English

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

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

update the xcode to 9.3 and I have problems with the programmable button 将xcode更新为9.3,我在使用可编程按钮时遇到问题

in Xcode 8 I have it in the following way and it works well 在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];

screen Xcode 8 enter image description here 屏幕Xcode 8 在此处输入图像描述

the image "settings.png" of the button shows me well with a height of 25 and width of 25. 按钮的图片“ settings.png”以25的高度和25的宽度很好地显示了我。

but when I actulice to xcode 9 does not take the initWithFrame: CGRectMake and it comes out much bigger. 但是当我使用xcode 9时,不要使用initWithFrame:CGRectMake,它会变得更大。 "the size of the button image “按钮图片的大小

screen Xcode 9.3 enter image description here 屏幕Xcode 9.3 在此处输入图像描述

How can i fix this? 我怎样才能解决这个问题?

You can resize image to be 25x25 您可以将图片大小调整为25x25

or 要么

just set content mode for Image 只需为图片设置内容模式

[[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:)];

solve it by placing 通过放置解决

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

When you call initWithCustomView , you are making a custom bar button item. 调用initWithCustomView ,您正在制作一个自定义栏按钮项。

  • In iOS 10 and before, this had a fixed size (based, as you rightly observe, on the frame ). 在iOS 10及更低版本中,它的大小是固定的(如您所正确看到的,基于frame )。

  • But in iOS 11, this behavior completely changes: iOS 11 uses auto layout to get the custom bar button item's size. 但是在iOS 11中,此行为完全改变了:iOS 11使用自动布局来获取自定义栏按钮项目的大小。

Therefore, you need to supply internal auto layout constraints (eg height and width constraints) that dictate the size of the custom view. 因此,您需要提供内部自动布局约束 (例如,高度和宽度约束),这些约束决定了自定义视图的大小。 If you give your button a height constraint of 25 and a width constraint of 25, all will be well. 如果将按钮的高度限制设置为25,宽度限制设置为25,那么一切都会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM