简体   繁体   中英

UIButton initWithFrame:CGRectMake not working in Xcode 9.3

update the xcode to 9.3 and I have problems with the programmable button

in Xcode 8 I have it in the following way and it works well

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

the image "settings.png" of the button shows me well with a height of 25 and width of 25.

but when I actulice to xcode 9 does not take the initWithFrame: CGRectMake and it comes out much bigger. "the size of the button image

screen Xcode 9.3 enter image description here

How can i fix this?

You can resize image to be 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.

  • In iOS 10 and before, this had a fixed size (based, as you rightly observe, on the frame ).

  • But in iOS 11, this behavior completely changes: iOS 11 uses auto layout to get the custom bar button item's size.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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