我有这个UIButton和一张图片。我不想让图片占据按钮内的所有空间,而只是在中间的一小部分,但如果我调整按钮的大小,它也会调整图像的大小。我该怎么做呢?有没有一个选项可以独立于UIButton的大小来设置我想要的任何尺寸?谢谢!
发布于 2016-11-10 03:57:57
这可以通过以下方式通过代码完成:
let imageSize:CGSize = CGSize(width: 20, height: 20)
let button:UIButton = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 200, y: 200, width: 60, height: 60)
button.backgroundColor = UIColor.yellow
button.setImage(UIImage(named: "chat.png"), for: UIControl.State.normal)
// The below line will give you what you want
button.imageEdgeInsets = UIEdgeInsets(
top: (button.frame.size.height - imageSize.height) / 2,
left: (button.frame.size.width - imageSize.width) / 2,
bottom: (button.frame.size.height - imageSize.height) / 2,
right: (button.frame.size.width - imageSize.width) / 2)
self.view.addSubview(button)这样,你就可以实现你想要的。
发布于 2016-11-10 03:22:26
您可以尝试使用图像视图插入。每个UIButton都有一个属性imageView。
在Swift 3中,你可以这样做:
//let button = UIButton()
button.imageView?.backgroundColor = UIColor.red
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)红色背景只是为了让你知道发生了什么变化
发布于 2020-07-28 03:27:31
我无法让按钮的imageView调整大小,直到我使用了contentHorizontalAlignment和contentVerticalAlignment,这两个参数都设置为.fill。然后使用imageEdgeInsets重新定位图像。
let button = UIButton()
let image = UIImage(systemName: "bag.badge.plus")
button.setImage(image, for: .normal)
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 10, right: 10)结果:

https://stackoverflow.com/questions/40514110
复制相似问题