iOS >> UIButton ImageView Property >> How to set Content Mode?

白昼怎懂夜的黑 提交于 2019-11-28 23:41:56

Using iOS7/8 with auto-layout, button.imageView doesn't get scaled when button is laid out, e.g. for iPhone 6:

(lldb) po button
<UIButton: 0x7fb4f501d7d0; frame = (0 0; 375 275); opaque = NO; autoresize = RM+BM; tag = 102; layer = <CALayer: 0x7fb4f501d160>>

(lldb) po button.imageView
<UIImageView: 0x7fb4f51d21f0; frame = (0 0; 0 0); clipsToBounds = YES; hidden = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7fb4f5152860>>

After setting button's image, button.imageView assumed the size of the image, e.g. for a 320x240 image:

(lldb) po button.imageView
<UIImageView: 0x7fb4f51d21f0; frame = (27.5 17.5; 320 240); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7fb4f5152860>>

It looks like button.imageView does not respect its content mode, but actually, it is the size of the button.imageView that is the problem.

The answer is to set button's content alignment as well.

The following sets button's image, sets button.imageView's content mode, and makes button.imageView fit the size of button:

[button setImage:image forState:UIControlStateNormal];
button.imageView.contentMode = UIViewContentModeScaleAspectFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

Now, button.imageView is the same size as button, and has the desired content mode.

(lldb) po button.imageView
<UIImageView: 0x7faac219a5c0; frame = (0 0; 375 275); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7faac219a6c0>>

The desired result is thereby achieved. Very handy!

if you don't want to subclass UIButton than you can try this,

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    for (UIView *view in button.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view setContentMode:UIViewContentModeScaleAspectFit];
        }
    }

Every UIButton has one hidden UIImageView of its own. So we have to set the content mode like the way given below...

[[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!