13

有没有办法设置 UIButton Image、BackgroundImage 或 ImageView 属性内容模式属性?

我已经尝试过直接的方法(它没有用,当然......):

self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;

有一个带有图像的按钮很好,但如果没有办法正确设置它,它就不是很方便......

4

3 回答 3

32

使用带有自动布局的 iOS7/8,在布局时button.imageView不会缩放button,例如对于 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>>

在设置button's image 之后,button.imageView假设图像的大小,例如对于 320x240 图像:

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

看起来button.imageView不尊重它的内容模式,但实际上,问题在于它的大小button.imageView

答案也是 setbutton的内容对齐。

以下设置button的图像,设置button.imageView的内容模式,并button.imageView适合 的大小button

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

现在,button.imageView大小与 相同button并且具有所需的内容模式。

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

从而达到期望的结果。非常便利!

于 2015-01-29T01:30:32.133 回答
2

如果你不想继承 UIButton 比你可以试试这个,

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    for (UIView *view in button.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view setContentMode:UIViewContentModeScaleAspectFit];
        }
    }
于 2014-01-03T13:58:41.373 回答
1

每个 UIButton 都有一个隐藏的 UIImageView。所以我们必须像下面给出的方式设置内容模式......

[[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
于 2017-07-15T12:11:09.103 回答