How do I scale a UIButton's imageView?

2019-01-10 02:23发布

I created a UIButton instance named "button" with an image using [UIButton setImage:forState:]. The button.frame is larger than the image's size.

Now I want to scale this button's image smaller. I tried changing button.imageView.frame, button.imageView.bounds and button.imageView.contentMode, but all seem ineffective.

Can anyone help me scale a UIButton's imageView?

I created the UIButton like this:

UIButton *button = [[UIButton alloc] init];
[button setImage:image forState:UIControlStateNormal];

I tried to scale the image like this:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.bounds = CGRectMake(0, 0, 70, 70);

and this:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.frame = CGRectMake(0, 0, 70, 70);

17条回答
三岁会撩人
2楼-- · 2019-01-10 02:57

For the original poster, here is the solution I found:

commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

This will allow your button to scale horizontally. There is a vertical setting as well.

Took me several hours to figure that one out (the naming of the property is very unintuitive) so figured I'd share.

查看更多
干净又极端
3楼-- · 2019-01-10 02:57

Storyboard

You must define specific property in Runtime Attributes of Identity inspectorimageView.contentModel, where you set value relatively to rawValue position of enum UIViewContentMode. 1 means scaleAspectFit.

Set button.imageView.contentMode in Storyboard

And button's alignment, in Attributes inspector:

Full alignment of button

查看更多
4楼-- · 2019-01-10 03:01

Screenshot in XCode 8

At the bottom left of screenshot, you can see Stretching properties. Try using those.

查看更多
干净又极端
5楼-- · 2019-01-10 03:03
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;
查看更多
甜甜的少女心
6楼-- · 2019-01-10 03:04

use

button.contentMode = UIViewContentModeScaleToFill;

not

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

Update:

As @Chris commented,

To get this to work for setImage:forState:, you need to do the following to scale horizontally: myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

查看更多
登录 后发表回答