有没有办法设置UIButton图像,BackgroundImage或ImageView属性内容模式属性?
我尝试过直接的方法(当然没有用......):
self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
有一个带图像的按钮很好,但是如果没有办法正确设置它,它就不是很方便......
答案 0 :(得分:28)
将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
的图像后,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
。
答案是设置button
的内容对齐方式。
以下设置button
的图片,设置button.imageView
的内容模式,并使button.imageView
符合button
的大小:< / p>
[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>>
由此实现了期望的结果。非常方便!
答案 1 :(得分:2)
如果您不想继承UIButton,那么可以试试这个,
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
for (UIView *view in button.subviews) {
if ([view isKindOfClass:[UIImageView class]]) {
[view setContentMode:UIViewContentModeScaleAspectFit];
}
}
答案 2 :(得分:0)
每个UIButton都有一个隐藏的UIImageView。所以我们必须像下面给出的方式设置内容模式......
[[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];