SWIFTUI。单击后如何永久更改按钮的颜色?

时间:2019-10-26 23:33:30

标签: button colors swiftui

我正在构建测验应用程序。一个问题; 3个答案。答案在单独的按钮中。

我设法单击按钮时更改了按钮的颜色。例如,从灰色到绿色/红色。但是单击后,按钮将恢复为灰色。

单击后是否可以保留更改后的颜色,例如HTML中的超链接?

这是样式代码:

struct MyButtonStyle: ButtonStyle {

  func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
      .padding(20)
      .foregroundColor(.white)
      .background(configuration.isPressed ? Color.red : Color.gray)
      .cornerRadius(10.0)

2 个答案:

答案 0 :(得分:1)

您可以这样声明您的ButtonStyle:

        if (snapshot.data != null) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max, //replace this to fill everything
            children: <Widget>[
              SizedBox(height: 15),
              Padding(
                padding: EdgeInsets.all(2.0),
                child: TriviaAutoSizeText(context, snapshot.data.Question),
              ),
              Spacer(), //add the spacer here 
                RadioButtonGroup(
                    labels: <String>[

然后在视图中,具有选择状态:

public struct SelectedButtonStyle: ButtonStyle {

    @Binding var isSelected: Bool

    public func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .foregroundColor(.white)
            .background(isSelected ? Color.red : Color.gray)
            .cornerRadius(10.0)
    }
}

然后您可以像这样声明您的按钮以使其一次被选中并永远保持选中状态:

@State var isSelected = false

或者您也可以像这样声明它也可以取消选择它:

Button("Tap") {
    self.isSelected = true
}   .buttonStyle(SelectedButtonStyle(isSelected: $isSelected))

答案 1 :(得分:0)

尝试类似的操作,一旦isPressed变为true,它就不会再次变为假,因此按钮将保持灰色状态

struct ContentView: View {

   @State private var isPressed = false

    var body: some View {
        Button(action: {
            self.isPressed = true
        }, label: {
            Text("Button").accentColor(isPressed ? Color.gray : Color.blue)
        })
    }
}