iOS >> UIButton ImageView属性>>如何设置内容模式?

Oha*_*gev 10 uibutton uiimageview contentmode ios

有没有办法设置UIButton图像,BackgroundImage或ImageView属性内容模式属性?

我尝试过直接的方法(它当然不起作用......):

self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*att 29

使用具有自动布局的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>>
Run Code Online (Sandbox Code Playgroud)

设置button图像后,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>>
Run Code Online (Sandbox Code Playgroud)

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

答案是设置button内容对齐方式.

以下设置button图像,设置button.imageView内容模式,并使其button.imageView符合以下大小button:

[button setImage:image forState:UIControlStateNormal];
button.imageView.contentMode = UIViewContentModeScaleAspectFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
Run Code Online (Sandbox Code Playgroud)

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

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

由此实现期望的结果.非常便利!


Hem*_*ora 2

如果你不想继承 UIButton 的子类,你可以尝试这个,

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