Why does a custom UIButton image does not resize i

2019-02-01 10:03发布

Why does a custom UIButton image not resize with the button?

I set its view mode to Scale to Fill in Interface Builder, but unlike a UIImageView image, it doesn't respect that setting.

Am I looking in the wrong place or is it not possible?

9条回答
在下西门庆
2楼-- · 2019-02-01 10:13

Just do (From Design OR From Code):

From Design

  1. Open your xib OR Storyboard.
  2. Select button
  3. Inside Attribute Inspector (Right side) > In "Control" section > select last 4th option for both Horizontal and Verical.

[For Point#3: Change Horizontal and vertical Align to UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]

From Code

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

查看更多
老娘就宠你
3楼-- · 2019-02-01 10:14

While this may not be quite what you're after - the background image does scale.

查看更多
不美不萌又怎样
4楼-- · 2019-02-01 10:22

Just get a real UIimageview and place a UIbutton on top of it and via layout menu set it to back. Then you can scale your image properly.

查看更多
贪生不怕死
5楼-- · 2019-02-01 10:23

Try this:

[button setImage:image forState:UIControlStateNormal];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

In Swift:

button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
查看更多
爷的心禁止访问
6楼-- · 2019-02-01 10:23

I know this is old, but I think that the correct answer is that you should set the content mode to the "hidden" UIImageView that is inside the UIButton:

button.imageView.contentMode = UIViewContentModeScaleAspectFill;

This will change the content mode for the images views of the images set with:

[button setImage:yourAwesomeImage forState:UIControlStateNormal]; 
//Or any other state
查看更多
戒情不戒烟
7楼-- · 2019-02-01 10:25

Interface Builder

To get images in UIButtons to scale the same way as UIViews in interface Builder follow these steps:

Select your UIButton and from the Identity Inspector add the following to User Defined Runtime Attributes:

imageView.contentMode Number 1

Where number is the enum number of contentMode, eg:

0 = Scale to fill 
1 = Aspect Fit 
2 = Aspect Fill
etc..

Then open the Attributes editor for your UIButton and under Control set the Alignment to Fill (last button on right) for both horizontal and vertical.

SWIFT 3

Note you can also do this in code with the following:

button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
查看更多
登录 后发表回答