文章

UIButton 设置图片在右的几种方法

UIButton的默认布局是图片在左,标题在右。想要得到一个图片在右,标题在做的UIButton,可以使用以下几种方法

方法一: 改变 Button 的语义属性

不同国家的文字书写方向不一样。在中国,文字书写方式是从左往右,因此UIButton的默认布局是图片在左;而在一些文字书写方向是从右往左的国家里,UIButton的默认布局是图片在右。UIView 有一个 semanticContentAttribute 属性,用来控制 View 的布局。我们可以将其强制更改为从右往左,这样 UIButton 的图片就在右边了:

1
btn.semanticContentAttribute = .forceRightToLeft

方法二: 写一个 UIButton 的子类,重写绘制方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
final class MyCustomTitleImageButton: UIButton {

    /// 是否把图片放在左边,默认关闭
    var isHeadBtn = false

    /// 是否显示箭头
    var needArrow = true

    var itemMaxWidth: CGFloat = 0

    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        if isHeadBtn {
            return super.titleRect(forContentRect: contentRect)
        } else {
            let superRect = super.titleRect(forContentRect: contentRect)
            var width = superRect.size.width
            let maxWidth = self.itemMaxWidth - (self.needArrow ? 16 : 0)
            if width > maxWidth {
                width = maxWidth
            }
            return CGRect(x: 0, y: frame.size.height / 2 - superRect.size.height / 2, width: width, height: superRect.size.height)
        }
    }

    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        if isHeadBtn {
            return super.imageRect(forContentRect: contentRect)
        } else {
            let superRect = super.imageRect(forContentRect: contentRect)
            return CGRect(x: frame.size.width - 18, y: frame.size.height / 2 - superRect.size.height / 2, width: superRect.size.width, height: superRect.size.height)
        }
    }
}

方法三: 利用 iOS 15.0 的新特性

上面的方法二在iOS 15之后的版本就要被废弃了。这时候可以利用iOS 15的新特性 UIButton.Configuration

1
2
3
4
5
6
        var config = UIButton.Configuration.plain()
        config.imagePlacement = .trailing	// 关键在这里
        config.title = "test"
        config.titleAlignment = .center
        config.image = UIImage(named: "icon_arrow")
        let btn2 = UIButton(configuration: config, primaryAction: nil)
本文由作者按照 CC BY-NC-SA 4.0 进行授权