UIButton doesn't listen to content mode settin

2019-01-10 07:16发布

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.

15条回答
ゆ 、 Hurt°
2楼-- · 2019-01-10 08:04

I also advice to have a look at the adjustsImageWhenHighlighted UIButton property to avoid weird deformations of the image, when the button is pressed.

查看更多
Bombasti
3楼-- · 2019-01-10 08:05

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.

查看更多
萌系小妹纸
4楼-- · 2019-01-10 08:06

Found a fix for this. Set the adjustsImageWhenHighlighted property of UIButton to NO.

  UIButton *b = [[UIButton alloc] initWithFrame:rect];
        [b setImage:image forState:UIControlStateNormal];
        [b.imageView setContentMode:UIViewContentModeScaleAspectFill];
        [b setAdjustsImageWhenHighlighted:NO];

Hope this helps. Feel free to comment below, I will follow up on any questions that you have.

查看更多
登录 后发表回答