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

标签 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)
  }
}

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

结果:

Red button on top of black button

关于ios - 如何在 SwiftUI 中提供自定义 ButtonStyle 附加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68106237/

相关文章:

swift - 突出显示两个 CollectionView 中的单元格

ios - 启动屏幕图像未出现在 SwiftUI 应用程序中

ios - 无法通过 xcode 安装来自其他开发人员的 api 文件

ios - 无法在 didUpdateNotificationStateForCharacteristic 中获取 CBcharacteristic 值

ios - 测试安装路径的 Firebase 深度链接

swift - Firestore - 使用 querySnaphot 中的 Int 值一次创建多个文档

ios - 无法更新 UILabel!在具有字符串值的 ViewController 中

swift - 执行核心数据的连接

ios - 如何添加将在swiftUI中位于所有 View 顶部的 View

ios - 在 SwiftUI 中暂停通知发布者