2

I have a button that has contentMode set to UIViewContentModeScaleAspectFill. I set it like this:

self.itemImage.imageView.contentMode = UIViewContentModeScaleAspectFill;

I also set it to Mode - Aspect Fill in IB for the button, just in case. And when I set the image, I DON'T set is as a background image:

[self.itemImage setImage:image forState:UIControlStateNormal];

However, occasionally my image does not fill the button (which I want it to do), like in this case:

enter image description here

See grey spaces on each side. Occurs on both iOS 6 and 7.

Any ideas?

artooras
  • 6,315
  • 9
  • 45
  • 78
  • itemImage is my UIButton name – artooras Jun 20 '14 at 14:25
  • Use self.itemImage.contentMode = UIViewContentModeScaleAspectFill; [self.itemImage setBackgroundImage:forState:]. – Yogendra Jun 20 '14 at 14:28
  • The image of a UIButton is only a part of the button. If you set an image and a text, they will appear next to each other. You could try to get rid of the spacing, but that would be hack-ish. – Klaas Jun 20 '14 at 14:30
  • @Klass, I don't use any text, only an image. And it works well for other buttons that are exactly the same. Can it be that the image is smaller than the button frame? Having said that, shouldn't ScaleAspectFill scale the image to fill the button anyway? – artooras Jun 20 '14 at 14:33
  • If I set it as backgroundImage, the image fills the button, but it is stretched and does not maintain the original aspect ratio. Can contentMode of backgroundImage be controlled separately? – artooras Jun 20 '14 at 14:59

1 Answers1

1

At long last, I managed to find the solution that works in Alfie's answer to this SO question.

In short, if your UIButton (or its hidden imageView) does not respond to contentMode, use this code:

self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
self.button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
Community
  • 1
  • 1
artooras
  • 6,315
  • 9
  • 45
  • 78