有没有办法设置UIButton
Image,BackgroundImage或ImageView属性内容模式属性?
我试过直接的方法(当然不行)…)
self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
有一个图像的按钮是很好的,但如果没有办法正确设置,这不是很方便…
解决方法
使用具有自动布局的iOS7 / 8,按钮布局时,button.imageView不会缩放比例.对于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.imageView假定图像的大小,例如一个320×240的图像:
(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.imageView的内容模式,并使button.imageView适合按钮的大小:
[button setImage:image forState:UIControlStateNormal]; button.imageView.contentMode = UIViewContentModeScaleAspectFill; button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
现在,button.imageView与按钮的大小相同,并且具有所需的内容模式.
(lldb) po button.imageView <UIImageView: 0x7faac219a5c0; frame = (0 0; 375 275); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7faac219a6c0>>
由此实现期望的结果.非常方便!