簡體   English   中英

如何在 SwiftUI 中提供自定義 ButtonStyle 附加選項

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM