在SwiftUI中点击更改按钮背景颜色

时间:2019-09-05 04:36:19

标签: swift xcode swiftui xcode11

我正在尝试在SwiftUI中更改Button的颜色。 这是我的整个CustomButton视图结构:

struct CustomButton: View {

    @State private var didTap:Bool = false

    var body: some View {
        Button(action: {
            self.didTap = true
        }) {

        Text("My custom button")
            .font(.system(size: 24))
        }
        .frame(width: 300, height: 75, alignment: .center)
        .padding(.all, 20)
        .background(Color.yellow)

        //My code above this comment works fine

        //I tried something like this, but it is not working
     //   if didTap == true {
     //   .background(Color.blue)
     //    }

    }
}

这是我的按钮的外观(很好):

My custom button

但是我的问题是:当用户点击此按钮时,如何更改背景颜色。

谢谢。

2 个答案:

答案 0 :(得分:6)

为此,您需要根据更改后的状态给出颜色:

struct CustomButton: View {

@State private var didTap:Bool = false

  var body: some View {
    Button(action: {
        self.didTap = true
    }) {

    Text("My custom button")
        .font(.system(size: 24))
    }
    .frame(width: 300, height: 75, alignment: .center)
    .padding(.all, 20)
    .background(didTap ? Color.blue : Color.yellow)
  }
}

PS::如果您也想管理其他状态,则可以使用enum

答案 1 :(得分:3)

以防万一有人希望以其他方式执行此操作。 它适用于更多颜色。

struct CustomButton: View {

    @State private var buttonBackColor:Color = .yellow

    var body: some View {
        Button(action: {

            //This changes colors to three different colors.
            //Just in case you wanted more than two colors.
             if (self.buttonBackColor == .yellow) {
                 self.buttonBackColor = .blue
             } else if self.buttonBackColor == .blue {
                 self.buttonBackColor = .green
             } else {
                 self.buttonBackColor = .yellow
             }

            //Same code using switch
            /*
             switch self.buttonBackColor {
             case .yellow:
                 self.buttonBackColor = .blue
             case .blue:
                 self.buttonBackColor = .green
             default:
                 self.buttonBackColor = .yellow
             }
             */
        }) {

        Text("My custom button")
            .font(.system(size: 24))
        }
        .frame(width: 300, height: 75, alignment: .center)
        .padding(.all, 20)
        .background(buttonBackColor)
    }
}
相关问题