firstButton is a UIButton of type Custom. I'm programmatically putting three of them across each cell of a table, thusly:
[firstButton setImage:markImage forState:UIControlStateNormal];
[firstButton setContentMode:UIViewContentModeScaleAspectFit];
[cell.contentView addSubview:firstButton];
Elsewhere, I'm telling it to clipToBounds. What I get is a crop of the center square of the image, rather than an aspect-scaled rendering of it. I've tried this lots of ways, including setting the mode property on firstButton.imageView, which also doesn't seem to work.
I believe we have a simple interface builder issue here - apparently the IB ignores any content-mode changes AFTER you have set the image-property.
the solution is as simple: set the content mode, remove previously set image-names (make sure you remove it in all states, default, highlighted etc.), then re-enter the desired image-names in all desired states - et voilà.
Instead of setImage try setBackgroundImage
Swift 3
The answer is to use a UIImageView with all the lovely Content Mode settings you want, and then layer a custom button on top of it. Dumb that you can't do that all in one shot, but it appears that you can't.
My answer is similar to Kuba's. I needed my image to be programatically set.
Rather than setting the
contentMode
on the button itself, you'll want to setcontentHorizontalAlignment
andcontentVerticalAlignment
properties and (crucially) thecontentMode
for the button'simageView
for any kind of aspect fill or fit. Here's an example:Of course, you can also do other things like aligning the button's image to the top of the button. If you don't need an aspect fill or fit, you just can set the alignment by itself:
In Swift, you'll want to use:
This works for all versions of iOS, including the latest versions with auto-layout, (i.e. iOS 4 up to iOS 11+).