2017-01-12 101 views
0

我创建了一个UIButton,使用图像作为按钮。但是,我无法调整图像/按钮的大小。我正在使用的代码是:UIButton Frame Not Resizing with Image

let leftArmImage = UIImage(named: "LeftArm") as UIImage? 
let leftArmButton = UIButton(type: UIButtonType.custom) as UIButton 
leftArmButton.frame = CGRect(x:self.view.center.x + 200,y:self.view.center.y,width:500,height:500) 
leftArmButton.setImage(leftArmImage, for: .normal) 
leftArmButton.imageView?.frame = leftArmButton.frame 
leftArmButton.addTarget(self, action: #selector(PhysicalExam.bodyPartSingleTapped(_:)), for:.touchUpInside) 
self.view.addSubview(leftArmButton) 

如何调整图像大小?

+0

你确定你的按钮还没有调整大小,但图像不包括该区域?尝试按下你认为按钮不在的区域,是否触发一个动作? (假设您已将操作附加到按钮上)编辑:您的图像设置为什么内容模式? – Jerland2

+2

尝试使用'leftArmButton.setBackgroundImage()'来代替'leftArmButton.setImage()',以便它可以覆盖整个按钮框架。 –

+0

@ Jerland2该按钮正在调整大小,但图像不是。按钮区域正确触发动作。至于图片的内容模式,我尝试了三种选择的循环,但没有一个填满框架。 – DMop

回答

1

而不是leftArmButton.setImage(),尝试使用leftArmButton.setBackgroundImage(),以便它可以覆盖整个按钮框架。

+0

这仍然不会填满按钮框架。我使框架可见,以便我可以验证这个 – DMop

0

试试这个

leftArmButton.imageView?.contentMode = .scaleAspectFill 
+0

它说UIContentMode没有成员'aspectFill' – DMop

+0

对不起,我不在我的电脑,但我更新了答案。如果它不起作用,只需输入'.'并等待xcode弹出选项以自动填充到AspectFill。 – Timmy

+0

没问题。这是一个选项,但它没有调整图像大小 – DMop

1

试试这个

编程

button.setImage(image, for: .normal) 
button.contentVerticalAlignment = .fill 
button.contentHorizontalAlignment = .fill 

故事板

  1. 打开你的故事板

  2. 选择属性检查器内部的按钮(右侧) - >在“控制”部分 - >选择水平和垂直对齐的第四选项(最后)。