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条回答
仙女界的扛把子
2楼-- · 2019-01-10 07:55

I believe we have a simple interface builder issue here - apparently the IB ignores any content-mode changes AFTER you have set the image-property.

the solution is as simple: set the content mode, remove previously set image-names (make sure you remove it in all states, default, highlighted etc.), then re-enter the desired image-names in all desired states - et voilà.

查看更多
冷血范
3楼-- · 2019-01-10 07:56

Instead of setImage try setBackgroundImage

查看更多
孤傲高冷的网名
4楼-- · 2019-01-10 07:59

Swift 3

self.firstButton.imageView?.contentMode = .scaleAspectFill
查看更多
乱世女痞
5楼-- · 2019-01-10 08:00

The answer is to use a UIImageView with all the lovely Content Mode settings you want, and then layer a custom button on top of it. Dumb that you can't do that all in one shot, but it appears that you can't.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-10 08:02

My answer is similar to Kuba's. I needed my image to be programatically set.

UIImage *image = [[UIImage alloc] initWithContentsOfFile:...];
[button setBackgroundImage:image forState:UIControlStateNormal];
button.imageView.contentMode = UIViewContentModeScaleAspectFill; //this is needed for some reason, won't work without it.
for(UIView *view in button.subviews) {
    view.contentMode = UIViewContentModeScaleAspectFill;
}
查看更多
Animai°情兽
7楼-- · 2019-01-10 08:04

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 = .fill
button.contentVerticalAlignment = .fill
button.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+).

查看更多
登录 后发表回答