我正在尝试在某些文本的左侧添加一个带有图标的按钮:
我对 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)
但是当你添加图片时
button.setImage(UIImage(named: "test"), for: .normal)
button.imageView!.backgroundColor = .clear
button.imageView!.contentMode = .scaleAspectFit
它保持原始大小 (300px) 并将标题从右侧推出按钮边界。 (无法在屏幕截图中看到它,因为它只显示按钮框架)
我做错了什么?为什么图像缩小后仍保持原来的宽度?如果 contentHorizontalAlignment
允许将项目推出框架,它还能做什么?
我知道您可以设置插图,但这是在可重复使用的 View 中使用的,因此我无法对值进行硬编码。
感谢帮助
最佳答案
我只是按照你说的做了一个按钮。
顺便说一句,你为什么不使用 inset。Apple 已经给了我们使用它的机会。那我们为什么不应该使用它呢?
注意:您必须反复试验才能正确定位图像和文本。
自动布局:
和插图:
如果它不准确,我说你必须反复试验。快乐的编码。 :)
关于ios - 带有图标和文本的 Swift UIButton(不使用 edgeinsets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420471/