A simple way to put a UIImage in a UIButton

Alice picture Alice · Dec 21, 2010 · Viewed 9.5k times · Source

I have a UIButton in my iPhone app. I set its size to 100x100.

I have an image that is 400x200 that I wish to display in the button.

The button STILL needs to stay at 100x100... and I want the image to downsize to fit... but keep the correct aspect ratio.

I thought that's what "Aspect Fit" was used for.

Do I include my image with setImage, or setBackgroundImage?

Do I set AspectFit for the button? or the image? or the background image?

(I need the smaller images to INCREASE in size. While larger images should DESCREASE in size. Always keeping the button at 100x100.)

I've tried countless combinations of all of the above... and I just can't seem to get everything to work at the same time:

  • Don't change the button's size of 100x100.
  • Don't destroy the image's aspect ratio.
  • Always increase small images to fit the button.
  • Always decrease large images to fit the button.
  • Never clip any of the image edges.
  • Never require the "put UIButtons over all your UIimages" hack.
  • Don't require everyone to upgrade to v4.2.1 just to use new framework methods.

I see so many apps, with so many fully-working image-buttons... that I can't believe I can't figure out this very simple, very common thing.

Ugh.

Answer

Dan Ray picture Dan Ray · Dec 21, 2010

UIButton is broken. That's the short answer. The UIImageViews in its image and backgroundImage properties don't respect UIViewContentMode settings. They're read-only properties, and while the UIImage contents of those UIImageViews can be set through setImage: and setBackgroundImage: methods, the content mode can't be.

The solution is either to provide properly-sized images in your bundle to begin with, or to put a UIImageView down, configure it the way you want it, and then put a clear "custom" UIButton over top of it. That's the hack all those fancy professional apps you've seen have used, I promise. We're all having to do it.