使用ButtonStyle,然后根据传递的配置值指定颜色和其他样式属性,即可实现您想要的外观。
如果存在一种可以继承默认按钮半径、基于文本长度自动调整宽度和其他属性的折中方案,那将是很好的,但至少有能力指定所有属性并获得所需的外观。
希望这有所帮助!
import SwiftUI
struct BlueButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(configuration.isPressed ? Color.blue : Color.white)
.background(configuration.isPressed ? Color.white : Color.blue)
.cornerRadius(6.0)
.padding()
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World")
.frame(maxWidth: .infinity, maxHeight: .infinity)
Button(action: {
}) {
Text("Press")
.frame(maxWidth: 100, maxHeight: 24)
}
.buttonStyle(BlueButtonStyle())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
受 @Gene Z. Ragan 巨佬的回答启发,我在此基础上做了更进一步的改动:
将 ButtonStyle 更加灵活化:
struct NiceButtonStyle: ButtonStyle {
var foregroundColor: Color
var backgroundColor: Color
var pressedColor: Color
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.font(.headline)
.padding(10)
.foregroundColor(foregroundColor)
.background(configuration.isPressed ? pressedColor : backgroundColor)
.cornerRadius(5)
}
}
然后在调用该方法时添加一些语法糖以使其更加清晰:
extension View {
func niceButton(
foregroundColor: Color = .white,
backgroundColor: Color = .gray,
pressedColor: Color = .accentColor
) -> some View {
self.buttonStyle(
NiceButtonStyle(
foregroundColor: foregroundColor,
backgroundColor: backgroundColor,
pressedColor: pressedColor
)
)
}
}
这意味着我们可以使用默认的颜色设置:白色前景、灰色背景以及强调颜色和按下颜色。
Button(action: { } ) {
Text("Button A")
}
.niceButton()
或者我们可以自定义颜色:
Button(action: { } ) {
Text("Button B has a long description")
}
.niceButton(
foregroundColor: .blue,
backgroundColor: .yellow,
pressedColor: .orange
)
我们得到:
再次感谢Gene。
Button(action: { } ) {
Text("Press")
.padding()
.background(Color.blue)
}
Button("Press"), action {}).buttonStyle(BluePaddingButtonStyle()
Button(action: { } ) {
Text("Press")
.padding()
.background(Color.blue)
}
.buttonStyle(.borderless)
来强制 macOS 上实现类似 iOS 的行为。Button(action: { } ) {
Text("Press")
.padding()
.background(Color.blue)
}
.buttonStyle(.borderless)
Text("Press")
.padding()
.background(Color.blue)
覆盖了“按钮”的“灰色背景”。
我的建议是,不要浪费时间 - 只需使用带有手势捕捉器的“标签”作为“按钮”。
Text("Press")
.padding()
.background(Color.blue)
.onTapGesture {
// reaction here
}