首页 > 解决方案 > 如何在 SwiftUI 中提供自定义 ButtonStyle 附加选项

问题描述

我目前有一个 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)
  }
}

我还有另一个 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)
  }
}

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

标签: iosswiftswiftui

解决方案


只需在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))
        }
    }
}

结果:

黑色按钮顶部的红色按钮


推荐阅读