我目前有一个 ButtonStyle 定义如下:
struct RoundedButtonRed: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
Spacer()
configuration.label.foregroundColor(.white)
Spacer()
}
.padding()
.background(Color.red.cornerRadius(13.0))
.scaleEffect(configuration.isPressed ? 0.85 : 1)
}
}
我还有另一个结构 (RoundedButtonBlack
),它有一个 .background(Color.black.cornerRadius(13.0))
,这似乎是不必要的代码重复。有没有办法添加自定义配置选项,以便我可以对不同的颜色使用相同的结构?
例如
struct RoundedButtonRed: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
Spacer()
configuration.label.foregroundColor(.white)
Spacer()
}
.padding()
.background(configuration.backgroundColor) // background color taken from configuration or passed into .buttonStyle(RoundedButton()) call
.scaleEffect(configuration.isPressed ? 0.85 : 1)
}
}
或者,也许有更好的方法?
最佳答案
只需在 RoundedButton
结构中添加一个属性来存储颜色。然后,当您使用 buttonStyle
应用它时,您可以传入任何您想要的颜色。
struct RoundedButton: ButtonStyle {
var color: Color /// add property here
func makeBody(configuration: Configuration) -> some View {
HStack {
Spacer()
configuration.label.foregroundColor(.white)
Spacer()
}
.padding() /// use it here
.background(color.cornerRadius(13.0))
.scaleEffect(configuration.isPressed ? 0.85 : 1)
}
}
struct ContentView: View {
var body: some View {
VStack { /// pass it in here
Button("Red button") {}.buttonStyle(RoundedButton(color: .red))
Button("Black button") {}.buttonStyle(RoundedButton(color: .black))
}
}
}
结果:
关于ios - 如何在 SwiftUI 中提供自定义 ButtonStyle 附加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68106237/