I am trying to change colour of my Button
in SwiftUI.
This is my whole CustomButton view struct:
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)
// }
}
}
This is what my button looks like (which is fine):
But my question is: how can I change the background colour when user taps this button.
Thank you.
Use HTML DOM Style backgroundColor Property to change the background color after clicking the button. This property is used to set the background-color of an element. Example: This example changes the background color with the help of JavaScript.
Method 1 − Using the storyboard editorAdd a button on your storyboard, select it Go to it's attribute inspector and select 'Background' property to choose the color.
To add a screen background view by putting it at the bottom of the ZStack. Text("Hello, SwiftUI!") <1> Use ZStack so we can place a background view under the content view. <2> Use color view as background.
To change a button's text color in SwiftUI we need to use . foregroundColor on our text view. In the above code it is almost the same as the simple button, but we used a modifier to change the foregroundColor to green. This needs to be on the Text and not on the Button view.
Just in case somebody wanted different way of doing this. It works for more colors.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With