I have a couple UIButtons, and in IB they\'re set to Aspect Fit, but for some reason they\'re always stretching. Is there something else you have to set? I tried all the d
This worked for me
[button.imageView setContentMode:UIViewContentModeScaleAspectFit];
Thanks to @ayreguitar for his comment
This method worked for me very well.:
In Xib select the button and set user defined runtime attributes
:
self.imageView.contentMode
Number
1
We use number because you cant use enum there. But the UIViewContentModeScaleAspectFit is equal to 1.
If you are doing this in Interface Builder, you can use the Runtime attributes inspector to set this directly without any code.
Set your Key Path on the button to be "imageView.contentMode" with a type of "Number" and a value of "1" (or whichever mode you would like).
Use button's imageView for contentMode. Not directly on the button itself.
homeButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
homeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
homeButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
[homeButton setImage:[UIImage imageNamed:kPNGLogo] forState:UIControlStateNormal];
UIView content modes apply to the corresponding CALayer's "content". This works for UIImageView
s because they set the CALayer
content to the corresponding CGImage
.
drawRect:
ultimately renders to the layer content.
A custom UIButton
(as far as I know) has no content (the rounded-rect style buttons might be rendered using content). The button has subviews: the background UIImageView
, the image UIImageView
, and the title UILabel
. Setting the contentMode
on the subviews may do what you want, but messing around with the UIButton
view hierarchy is a bit of a no-no.
Changing UIButton.imageView.contentMode
does not worked for me.
I solved the problem by setting the image to 'Background' property.
You can add ratio constraint if you need