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

wil*_*lc2 44 cocoa-touch interface-builder uibutton ios

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

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

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

tea*_*bot 82

虽然这可能不是你想要的 - 背景图像确实可以扩展.

  • 如果您不愿意使用背景图像(因为您要为不同的状态使用不同的图像),则需要设置alignment属性.请参阅:http://stackoverflow.com/questions/1957317/how-do-i-scale-a-uibuttons-imageview/8179900#8179900 (2认同)
  • 如果您希望它缩放以适应怎么办?然后缩放以填充的背景图像将不合适 (2认同)

Cao*_*Loc 54

试试这个:

[button setImage:image forState:UIControlStateNormal];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
Run Code Online (Sandbox Code Playgroud)

在Swift中:

button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
Run Code Online (Sandbox Code Playgroud)

  • 它也可以通过这种方式在界面构建器中工作;) (3认同)

drp*_*elo 37

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

在此处设置按钮的控制对齐设置


Md *_*ury 31

在属性检查器中首先设置类型“ Custom”和样式“ Default”,然后设置水平和垂直对齐方式“ fill”。

在此输入图像描述

  • 这是 2022 年的正确答案,其他答案都不再正确。 (2认同)
  • 2023 年也证实了这一点。 (2认同)

Ras*_*spu 12

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

button.imageView.contentMode = UIViewContentModeScaleAspectFill;
Run Code Online (Sandbox Code Playgroud)

这将更改图像集的图像视图的内容模式:

[button setImage:yourAwesomeImage forState:UIControlStateNormal]; 
//Or any other state
Run Code Online (Sandbox Code Playgroud)


San*_* SM 10

只做(来自设计或来自代码):

来自设计

  1. 打开你的xib或故事板.
  2. 选择按钮
  3. 内部属性检查器(右侧)>在"控制"部分> 为水平和Verical 选择最后的第4个选项.

[对于点#3:更改水平和垂直对齐到UIControlContentHorizo​​ntalAlignmentFill和UIControlContentVericalAlignmentFill]

从代码

button.contentHorizo​​ntalAlignment = UIControlContentHorizo​​ntalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

  • 有趣的是,在 XIB 查看器中,它看起来没有缩放。事实上,它会将按钮放大到更大的尺寸,但在运行时它会缩放到它应该的尺寸。 (2认同)

Geo*_*kos 6

界面生成器

要在UIButtons中获取图像以按与Interface Builder中的UIViews相同的方式缩放,请遵循以下步骤:

选择您的UIButton,然后从Identity Inspector中将以下内容添加到User Defined Runtime Attributes中

imageView.contentMode数字1

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

0 = Scale to fill 
1 = Aspect Fit 
2 = Aspect Fill
etc..
Run Code Online (Sandbox Code Playgroud)

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

SWIFT 3

请注意,您还可以使用以下代码在代码中执行此操作:

button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
Run Code Online (Sandbox Code Playgroud)