如何在 SwiftUI 中提供自定义 ButtonStyle 附加选项

and*_*824 4 ios swift swiftui

我目前有一个 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

我还有另一个 struct ( 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,也许还有更好的方法?

ahe*_*eze 11

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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

黑色按钮上方的红色按钮