UIButton doesn't listen to content mode setting? UIButton doesn't listen to content mode setting? ios ios

UIButton doesn't listen to content mode setting?


I had the same problem. I see this question is a little old, but I want to provide a clear and correct answer to save other folks (like me) some time when it pops up in their search results.

It took me a bit of searching and experimenting, but I found the solution. Simply set the ContentMode of the "hidden" ImageView that is inside the UIButton.

[[firstButton imageView] setContentMode: UIViewContentModeScaleAspectFit];[firstButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];

Perhaps that's what Dan Ray was alluding to in his accepted answer, but I suspect not.


If you're dealing with the UIButton's image (as opposed to it's backgroundImage), setting the contentMode on the UIButton itself or on its imageView has no effect (despite what other answers say).

Alternatively do this instead:

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

Or size your image accordingly.

OR just use a UIImageView (which properly respects contentMode) with a UITapGestureRecognizer attached to it, or a transparent UIButton on top of it.


Rather than setting the contentMode on the button itself, you'll want to set contentHorizontalAlignment and contentVerticalAlignment properties and (crucially) the contentMode for the button's imageView for any kind of aspect fill or fit. Here's an example:

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;button.imageView.contentMode = UIViewContentModeScaleAspectFit;

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:

button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

In Swift, you'll want to use:

button.contentHorizontalAlignment = .fillbutton.contentVerticalAlignment = .fillbutton.imageView?.contentMode = .scaleAspectFit

This works for all versions of iOS, including the latest versions with auto-layout, (i.e. iOS 4 up to iOS 11+).