为什么自定义UIButton图像不能在Interface Builder中resize?

为什么自定义的UIButton图像不能用buttonresize?

我将其视图模式设置为缩放以填充界面生成器,但与UIImageView图像不同,它不尊重该设置。

我看错了地方还是不可能?

虽然这可能不完全是你以后的事情 – 背景图像的规模。

尝试这个:

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

请记住设置button的控制alignment设置

这里设置按钮的控制对齐设置

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

 button.imageView.contentMode = UIViewContentModeScaleAspectFill; 

这将改变设置图像的图像视图的内容模式:

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

只要做(从devise或从代码):

从devise

  1. 打开你的xib或Storyboard。
  2. selectbutton
  3. 内部属性检查器 (右侧)>在“控制”部分>水平和Vericalselect最后第四个选项

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

从代码

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

界面生成器

要在UIButtons中获取图像以与在Interface Builder中的UIViews相同的方式进行缩放,请按照下列步骤操作:

select你的UIButton,并从Identity Inspector中添加以下内容到用户定义的运行时属性

imageView.contentMode数字1

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

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

然后打开你的UIButton的属性编辑器,并在控制下设置水平和垂直的alignment填充(最后一个button)。

SWIFT 3

注意你也可以用下面的代码来做到这一点:

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

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

希望有所帮助。

我在Swift 2.1中发现的最佳解决scheme如下:

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

这将缩放图像,使其在imageView中有一个方面。

只要得到一个真正的UIimageview,并在其上放置一个UIbutton,并通过布局菜单将其设置回来。 然后你可以正确地缩放你的图像。