[英]How can I give a custom ButtonStyle in SwiftUI additional options
我目前有一個 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))
}
}
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.