17

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

My custom button

But my question is: how can I change the background colour when user taps this button.

Thank you.

0ndre_
  • 3,577
  • 6
  • 26
  • 44

4 Answers4

23

For doinng this you need to give the colour as per the state changed:

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: If you want to manage other states too then you can go for the enum.

N.Cookie
  • 246
  • 2
  • 4
  • Is there any way to reset the color back after a tap? – pizzae May 10 '20 at 14:54
  • @pizzae instead of doing `self.didTap = true` use `self.didTap.toggle()` and then it will switch back and forth on each tap. – jwknz Jun 06 '20 at 08:17
  • @jwknz Does that mean you have to tap it again, i.e. a total of 2 times to get to the original color? Is there a way to make it so that it changes color back instantly after a single tap? – pizzae Jun 06 '20 at 08:35
  • @pizzae Well it won’t change back to the original color unless you set that color to be the value of false - so then yes that would be 2 taps. If you want it to change back after a period of time then you can use timer and set it back after a number of seconds or whatever it is you want it to achieve. – jwknz Jun 06 '20 at 08:38
7

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)
    }
}
0ndre_
  • 3,577
  • 6
  • 26
  • 44
0

But in the new Ways, or in the new version of Swift, Xcode, and iOS, you just have to write .color_name, if you will use class, like above, then it will generate errors.

In the Struct class just add in the 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)
        )
}
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
HEMANT KUMAR
  • 34
  • 1
  • 4
0

Did this a while ago based on a quiz making app. If the user got an answer correct, it would turn a button green, if wrong, turns the button red. The same could work for just a clickable button as well by removing the elif statement.

    @IBAction func answerButtonPressed(_ sender: UIButton) {
    
    
    let actualAnswer = quiz[questionNumber].a
    let buttonPressed = sender.currentTitle!

    
    if buttonPressed == actualAnswer {
        print("Right")
        sender.backgroundColor = UIColor.green
    } else {
        print("wrong")
        sender.backgroundColor = UIColor.red
    }