ios - 带有图标和文本的 Swift UIButton(不使用 edgeinsets)

标签 ios swift xcode8

我正在尝试在某些文本的左侧添加一个带有图标的按钮:

enter image description here

我对 UIButton 的理解有问题。向按钮添加标题效果很好:

import UIKit

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 25))
button.backgroundColor = .green
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .fill
button.titleLabel!.backgroundColor = .blue
button.setTitle("639", for: .normal)
button.setTitleColor(.white, for: .normal)

enter image description here

但是当你添加图片时

button.setImage(UIImage(named: "test"), for: .normal)
button.imageView!.backgroundColor = .clear
button.imageView!.contentMode = .scaleAspectFit

enter image description here

它保持原始大小 (300px) 并将标题从右侧推出按钮边界。 (无法在屏幕截图中看到它,因为它只显示按钮框架)

我做错了什么?为什么图像缩小后仍保持原来的宽度?如果 contentHorizo​​ntalAlignment 允许将项目推出框架,它还能做什么?

我知道您可以设置插图,但这是在可重复使用的 View 中使用的,因此我无法对值进行硬编码。

感谢帮助

最佳答案

我只是按照你说的做了一个按钮。

顺便说一句,你为什么不使用 inset。Apple 已经给了我们使用它的机会。那我们为什么不应该使用它呢?

注意:您必须反复试验才能正确定位图像和文本。

enter image description here

自动布局:

enter image description here

和插图:

enter image description here

如果它不准确,我说你必须反复试验。快乐的编码。 :)

关于ios - 带有图标和文本的 Swift UIButton(不使用 edgeinsets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420471/

相关文章:

swift - 嵌入式 TableViewController 上未显示导航栏 - Swift

ios - 是否存在标准 iOS 弹出窗口以启用访问位置?

iphone - 具有视频和音频的应用程序的本地化

ios - HKWorkoutSession 中的心率数据是移动平均值吗?

iOS 应用总是使用(错误的)本地化

ios - Xcode 8 中没有这样的模块 'CryptoSwift'

ios - 图片只全屏显示一次

ios - 更改 iOS 模拟器的默认 JavaScript 编辑器

ios - skemitternode 与 skspritenode 的碰撞

swift - 赋予 SKNode 自己的物理特性