SwiftUI 中 Button 会根据其内容自动适应大小和点击范围,这样导致有时需要水平等分布局的时候,文字长度不一样,导致按钮大小不一样。
只是单纯的设置 frame 并不能像想象中解决问题,除非使用其他的 View 自定义按钮。
使用 ButtonStyle 来封装与按钮样式相关的内容。 指定 .frame(maxWidth: .infinity) 让这个按钮尽可能占据整个宽度
1
2
3
4
5
6
7
8
9
10
11
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.headline.bold())
.foregroundColor(.white)
.frame(height: 50)
.frame(maxWidth: .infinity)
.background(Color.purple)
.cornerRadius(10)
}
}
两个按钮水平等分布局,两个按钮设置 maxWidth: .infinity,那么它们将被平均划分,间距由 HStack 的 spacing 指定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct ContentView: View {
var body: some View {
HStack(spacing: 30) {
Button(action: {}) {
Text("取消")
.font(.title2)
}
.buttonStyle(CustomButtonStyle())
Button(action: {}) {
Text("确认删除")
.font(.title2)
}
.buttonStyle(CustomButtonStyle())
}
.padding(20)
}
}
结果如下