iosuibuttoncontentmode

UIButton doesn't listen to content mode setting?


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.


Solution

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