UIButton initWithFrame:CGRectMake not working in Xcode 9.3

349 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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 (e.g. 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.

0
On

Is there a problem in adding a bar button item like :-

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

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];
0
On

solve it by placing

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