Kri*_*aCA 14
这可以通过以下方式通过代码完成:
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)
Run Code Online (Sandbox Code Playgroud)
这样,您就可以实现自己想要的目标.
您可以尝试使用图像视图插图.每个UIButton都有一个属性imageView.
在Swift 3中你可以这样做:
//let button = UIButton()
button.imageView?.backgroundColor = UIColor.red
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
Run Code Online (Sandbox Code Playgroud)
红色背景只是让你知道什么是变化
在我使用 contentHorizontalAlignment 和 contentVerticalAlignment 都设置为 .fill 之前,我无法让按钮的 imageView 调整大小。然后使用 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)
Run Code Online (Sandbox Code Playgroud)
结果:
我会这样:
A UIButton只是一个UIView。你可以简单地添加UIImageView了一组图像和呼叫addSubview上UIButton。
考虑到 KVISH 在我实施之前所说的,并且它按预期工作。我发布此内容是因为 Houman 要求提供示例。
//grab the image using the name of the pic
var image = UIImage(named: "picture")
//set the size for the image
image = image?.resize(toWidth: 18)
image = image?.resize(toHeight: 18)
//set the image to the button
buttonName.setImage(image, for: UIControlState.normal)
//adjust the position
buttonName.imageEdgeInsets = UIEdgeInsetsMake(8,16,9,0)
Run Code Online (Sandbox Code Playgroud)
从 iOS 13 开始,当使用 SF Symbols 时,我更喜欢这样:
let button = UIButton()
let font = UIFont.systemFont(ofSize: 30) // <- make it larger, smaller, whatever you want.
let config = UIImage.SymbolConfiguration(font: font)
let image = UIImage(systemName: "bag.badge.plus", withConfiguration: config)
button.setImage(image, for: .normal)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21121 次 |
| 最近记录: |