iOS>> UIButton ImageView属性>>如何设置内容模式? [英] iOS >> UIButton ImageView Property >> How to set Content Mode?

查看:178
本文介绍了iOS>> UIButton ImageView属性>>如何设置内容模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to set a UIButton Image, BackgroundImage or ImageView Properties Content Mode Property?

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

I've tried the direct approach (it didn't work, of course...):

self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;

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

It's nice to have a button with an image, but if there's no way to set it properly, it's not very handy...

推荐答案

使用iOS7 / 8进行自动布局, button.imageView 在布置按钮时不会缩放,例如对于iPhone 6:

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>>

设置按钮的图像后, button.imageView 假设图像的大小,例如对于320x240图像:

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>>

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

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.

以下设置按钮的图像,设置 button.imageView 的内容模式,然后设置按钮.imageView 符合按钮的大小

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;

现在, button.imageView 是一样的尺寸为按钮具有所需的内容模式。

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!

这篇关于iOS&gt;&gt; UIButton ImageView属性&gt;&gt;如何设置内容模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆