Learn Courses My Dashboard

Changing a button's appearance when pressed

Please help. I can’t figure out how to change a button’s modifiers when it is pressed. I want some kind of change on the button to indicate that it is off or on (different foreground or background color perhaps). I looked up the toggle command but if I use that as a button then I don’t know how to assign an action to it like a real button. I hope that makes sense. I’m obviously a beginner.

This code does not work but it gives an idea of what I am trying to do.


struct PESelect: View {
    
    @State private var isOn = false
    var body: some View {

        Button(action: {
            if isOn == false { foregroundColor(Color.red)}})
            {Text("no sweats")
                .frame(maxWidth: .infinity)
        }
            .buttonStyle(PlainButtonStyle())
        }
}

This might give you an idea of how to flip the foreground and background colors based on isOn being toggled by the Button press.

struct PESelect: View {

    @State private var isOn = false

    var body: some View {

        Button(action: {
            isOn.toggle()
        }) {
            Text("No Sweats")
                .font(.largeTitle)
                .bold()
                .foregroundColor(isOn ? Color.red : Color.black)
        }
        .frame(width: 250, height: 60)
        .background(isOn ? Color.yellow : Color.red)
        .cornerRadius(10)
    }
}

Thank you. This is very helpful