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

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

问题描述

有没有办法设置 UIButton Image、BackgroundImage 或 ImageView 属性 Content Mode 属性?

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 button 无法缩放布局,例如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的图片后,button.imageView假设图片的大小,e.g.对于 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的图片,设置button.imageView的内容模式,使button.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.imageViewbutton 大小相同,并且 具有所需的内容模式.

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天全站免登陆