首页 > 解决方案 > 定位 UIButton 的内部图像

问题描述

我在 UIButton 中添加了一个方形图像。目标是在按钮的左侧有方形图像,按钮的 4 边周围有空间边距 = 5。

这是代码:

button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .left;
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)

在界面构建中,我尝试在“控制”中左对齐,或者使用插图无济于事。

结果如下:

在此处输入图像描述

您会注意到几个问题:

  1. 右边距 > 5(在按钮和文本之间)
  2. 左边距 > 5
  3. 其余部分、方面以及顶部和底部边距都很好。

如何将这个按钮很好地放在左边,而文字就在它旁边?

标签: iosswiftuibutton

解决方案


首先,调整按钮图像资源的大小以按比例校正 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


推荐阅读