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

Change button background colour on tap in SwiftUI

我正在尝试在 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)
     //    }

    }
}

这是我的按钮的样子(很好):

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

谢谢。

为此,您需要根据已更改的状态提供颜色:

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.

以防万一有人想要不同的方式来做这件事。 它适用于更多颜色。

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

但是在新的方法中,或者在Swift、Xcode和iOS的新版本中,你只需要写.color_name,如果你愿意的话使用class,像上面一样,那么它会产生错误。

在结构 class 中只需添加 ContentView: View:

@State private var didTap:Bool = false

Button(action:{
    self.didTap = true
}) {
    Text("ಕನ್ನಡ").font(.system(size: 17))
        .fontWeight(.bold)
        .foregroundColor(didTap ? .orange :.black)
        .frame(minWidth: 0, maxWidth:143)
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 10)
                .fill(Color.white)
                .shadow(color: .gray, radius: 2, x: 0, y: 2)
        )
}