ios - 定位 UIButton 的内部图像
问题描述
我在 UIButton 中添加了一个方形图像。目标是在按钮的左侧有方形图像,按钮的 4 边周围有空间边距 = 5。
这是代码:
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .left;
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
在界面构建中,我尝试在“控制”中左对齐,或者使用插图无济于事。
结果如下:
您会注意到几个问题:
- 右边距 > 5(在按钮和文本之间)
- 左边距 > 5
- 其余部分、方面以及顶部和底部边距都很好。
如何将这个按钮很好地放在左边,而文字就在它旁边?
解决方案
首先,调整按钮图像资源的大小以按比例校正 x2 或 x3。那就试试这门课。
class DefaultButton: UIButton {
@discardableResult
func setImage(_ image: UIImage?) -> Self {
if let image = image {
self.imageView?.contentMode = .center
self.setImage(image, for: .normal)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
self.contentHorizontalAlignment = .left
self.titleEdgeInsets.left = (frame.width - (imageEdgeInsets.left + imageView!.frame.width) - titleLabel!.frame.width) / 2
}
return self
}
}
let button = DefaultButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 110, height: 60)
button.setTitle("FRANCE", for: .normal)
button.setImage(UIImage(named: "france"))
这是我实现此类 UI 的仓库,您可以参考 https://github.com/haphanquang/FigmaKit
推荐阅读
- mysql - 如何从 SQL Server 生成 XML 日志文件
- python - pip 包在 OSX 中创建可执行文件,但在 Ubuntu 中没有
- python - 根据条件加入有或没有最后一个元素的列表的pythonic方法
- java - 设置kafka主题过滤器
- html - 如何使用 li 和 ul 标签从 Selenium 的下拉列表中选择值?
- signal-processing - WebAudio API / javascript中低频信号的快速傅立叶变换
- spring - Spring Security @PreAuthorize 在将验证器 bean 添加到 WebDataBinder 时将其设置为 null
- java - IntelliJ 调试器不会在 Maven 项目的断点处暂停
- css - 如何在 CSS Grid 中隐藏内容?
- multithreading - 在 Google Cloud 上订阅不足时减少执行时间