iosuiimageviewcontentmode

AspectFill does not fill the UIImageView


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?


Solution

  • 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;