截止目前(2021-10-16
)为止,要想实现下面的几种 button
样式(这里要考虑图片和文字间距),我所知道的方案有两种:
-
给 UIButton
添加分类
-
自定义 UIButton
而在实际开发中,我们使用 方案1 应该是最多的!

自我参加工作(2015-06
)以来,对于 UIButton
如上图的需求就一直有,而且还有很多!说实话,我也一直困惑,苹果爸爸问什么不支持一下呢?
也许是有人不停地给苹果爸爸提 issue
,
也许是苹果爸爸也遇到大量的如此需求,
也许苹果爸爸做了统计发现几乎所有 APP
都有 UIButton
这类 Categroy
(Swift
是 Extension
),
也许苹果爸爸终于闲了有时间管了,
也许…,
不管怎么说,iOS15
,苹果爸爸支持了!而且API
也如预期的那样简单:
1
2
3
4
5
6
|
var conf = UIButton.Configuration.borderedTinted()
/// 设置图片的摆放(图片在上,则文字在下)
conf.imagePlacement = .top
/// 设置图片和文字的间距
conf.imagePadding = 10
let bt = UIButton.init(configuration: conf, primaryAction: nil)
|
插一句:对于 configuration
这样的 API
设计,我是非常认可的,一看就知道是干什么用的!感觉苹果爸爸也有意如此设计,比如 iOS14
开始的的 PHPickerConfiguration
等。
而我能发现这个,源自今天(2021-10-16
)下午,打算用 Swift
重写老项目(《酷乐潮玩》)的一个推荐列表页,其中 cell
上有如下几个按钮,我想参考 OC
写的 UIButton
的 category
,也写个 Swift
版的:



可是,在敲 titleedg
时,竟提示 'titleEdgeInsets' will be deprecated in iOS 15.0
。这瞬间激起了我的兴趣,于是点击进去一探究竟!

Swift
版 UIButtonConfiguration
:

Objective-C
版 UIButtonConfiguration
:

于是,我粗略地写了个 demo
验证一下,最终效果图:

具体代码如下:
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
test()
}
func test() {
var conf1 = UIButton.Configuration.plain()
conf1.title = "点赞"
conf1.image = UIImage(named: "liked")
conf1.imagePlacement = .leading
conf1.imagePadding = 10
let bt1 = UIButton.init(configuration: conf1, primaryAction: nil)
var conf2 = UIButton.Configuration.bordered()
conf2.title = "点赞"
conf2.image = UIImage(named: "liked")
conf2.imagePlacement = .trailing
conf2.imagePadding = 40
let bt2 = UIButton.init(configuration: conf2, primaryAction: nil)
var conf3 = UIButton.Configuration.borderedTinted()
conf3.title = "点赞"
conf3.image = UIImage(named: "liked")
conf3.imagePlacement = .top
conf3.imagePadding = 10
let bt3 = UIButton.init(configuration: conf3, primaryAction: nil)
var conf4 = UIButton.Configuration.gray()
conf4.title = "点赞"
conf4.image = UIImage(named: "liked")
conf4.imagePlacement = .bottom
conf4.imagePadding = 10
let bt4 = UIButton.init(configuration: conf4, primaryAction: nil)
bt1.frame = CGRect(x: 50, y: 100, width: 100, height: 80)
bt2.frame = CGRect(x: 200, y: 100, width: 150, height: 80)
bt3.frame = CGRect(x: 50, y: 230, width: 100, height: 80)
bt4.frame = CGRect(x: 200, y: 230, width: 100, height: 80)
view.addSubview(bt1)
view.addSubview(bt2)
view.addSubview(bt3)
view.addSubview(bt4)
}
}
|
最后,话又说回来了,目前我们的 APP
不可能是从 iOS15
开始的,估计大多数是从 iOS11
开始的,还有一部分是从 iOS9
开始,也有一部分是从 iOS13
开始的,所以 做好兼容还是很有必要的!
而更多关于 UIButton
的新知,请自行查看 API
学习,总体感觉:UIButton更丰富多彩了 !