Ios – How to prevent a button’s background image from stretching

cocoa-touchiosuibuttonuiimageviewuikit

I'm allocating a UIButtonTypeCustom UIButton to a UIView with a background image that is smaller than the button's frame. Reason why the image is smaller is because I'm trying to add more of a "target area" for the UIButton. However, the image is being scaled to the full size of the frame, rather than just being the image's size.

I have tried setting the UIButton and UIButton's imageView contentMode property to "UIViewContentModeScaleAspectFit", but no luck, the image still gets stretched out.

Is there a way to do what I'm trying to do programmatically?

Thanks in advance!

Best Answer

A lot of people make the same mistake you do in regards to button images and then jump through hoops trying to make the button behave as they expect it to. Let's clear this up once and for all:

A UIButton has two types of images it can display -- a foreground image and a background image. The background image for a button is expected to replace the button's background texture. As such, it makes sense that it stretches to fill the entire background. However, the button's foreground image is expected to be an icon that may or may not display alongside text; it will not stretch. It may shrink if the frame is smaller than the image, but it will not stretch. You can even set the alignment of the foreground image using the Control alignment properties in Interface Builder.

A button's foreground and background image can be set in code like this:

// stretchy
[self setBackgroundImage:backgroundImage forState:UIControlStateNormal];  

// not stretchy
[self setImage:forgroundImage forState:UIControlStateNormal];