有没有办法让按钮背景颜色在被选中后保持不变?

Is there a way for a button background color to remain changed after being selected?

以下代码在按下时更改按钮背景颜色,但在释放时返回原始背景。我希望按钮保持选中状态。

struct MyButtonStyle: ButtonStyle {

func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .padding()
      .foregroundColor(configuration.isPressed ? Color.white : Color("greenColor"))
      .background(configuration.isPressed ? Color.red : Color.clear)
  }

}

这是一个可能的解决方案,不使用自定义按钮。如果点击按钮,只需跟踪 State 变量即可。第一个按钮使用 plain 样式和 cornerRadius,第二个按钮使用 borderedProminent 样式,但在按钮点击时显示突出显示。

struct ContentView: View {
    @State var firstbutton: Bool = false
    @State var secondbutton: Bool = false
    // AppStorage saves state when app is killed
    //@AppStorange("tapped") var tapped: Bool = false
    var body: some View {
        Button(action: {
            firstbutton.toggle()
            /*
             if once
             toggle = true
             */
        }, label: {
            Label("Button", systemImage: "square.and.arrow.up")
                .foregroundColor(firstbutton ? Color.white : Color.green)
                .padding(.all, 10)
        })
        .background(firstbutton ? Color.red : Color.clear)
        .cornerRadius(5)
        .buttonStyle(.plain)
        
        
        Button(action: {
            secondbutton.toggle()
            /*
             if once
             toggle = true
             */
        }, label: {
            Label("Button", systemImage: "square.and.arrow.up")
                .foregroundColor(secondbutton ? Color.white : Color.green)
                .padding(.all, 10)
        })
        .tint(secondbutton ? Color.red : Color.clear)
        .buttonStyle(.borderedProminent)
    }
}

我们可以通过在按钮样式中引入状态并根据它进行样式更改,同时在需要时有条件地更新状态来做到这一点。

这是方法的主要部分(使用 Xcode 13.3 / iOS 15.4 测试)

    .background(flag ? Color.red : Color.clear)
    .onChange(of: configuration.isPressed) {
        if [=10=] {
            flag.toggle()
        }
    }

完成report and code is here