为什么自定义UIButton图像不会在Interface Builder中调整大小?

时间:2009-06-30 10:44:51

标签: ios cocoa-touch uibutton interface-builder

为什么自定义UIButton图像不会随按钮调整大小?

我在Interface Builder中将其视图模式设置为 Scale to Fill ,但与UIImageView图像不同,它不尊重该设置。

我是在寻找错误的地方还是不可能?

9 个答案:

答案 0 :(得分:78)

虽然这可能不是您想要的 - 背景图片缩放。

答案 1 :(得分:51)

试试这个:

[button setImage:image forState:UIControlStateNormal];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

在Swift中:

button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill

答案 2 :(得分:33)

请记住为按钮设置控制对齐设置

here set Control Alignment settings for the button

答案 3 :(得分:11)

我知道这是旧的,但我认为正确的答案是你应该将内容模式设置为UIButton中的“隐藏”UIImageView:

button.imageView.contentMode = UIViewContentModeScaleAspectFill;

这将更改使用以下项目设置的图像的图像视图的内容模式:

[button setImage:yourAwesomeImage forState:UIControlStateNormal]; 
//Or any other state

答案 4 :(得分:5)

界面生成器

要在UIButtons中获取图像以与界面生成器中的UIViews相同的方式进行缩放,请按照以下步骤操作:

选择您的UIButton,然后从 Identity Inspector 中将以下内容添加到用户定义的运行时属性

imageView.contentMode Number 1

其中number是contentMode的枚举数,例如:

0 = Scale to fill 
1 = Aspect Fit 
2 = Aspect Fill
etc..

然后打开UIButton的属性编辑器,并在控制下将对齐设置为填充(右侧的最后一个按钮)垂直。

SWIFT 3

请注意,您也可以在代码中执行以下操作:

button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill

答案 5 :(得分:2)

更新本文将为Swift 5提供完整答案:

clang

答案 6 :(得分:0)

尝试将Interface Builder中的Clip子视图属性设置为true。

希望有所帮助。

答案 7 :(得分:-2)

我在Swift 2.1中找到的最佳解决方案如下:

self.imageButton.imageView?.clipsToBounds = true
self.imageButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit

这将缩放图像,使其具有适合imageView的宽高比。

答案 8 :(得分:-5)

只需获得一个真实的UIimageview并在其上放置一个UI按钮,然后通过布局菜单将其设置为返回。然后,您可以正确缩放图像。