Button That Changes Label on Click

So I’ve looked this up so many times and tried every way I’ve found using a @State variable and nothing works. I need a button that toggles between SystemImage: “Star” to SystemImage: “Star.fill” when clicked. And I want it to happen when it’s clicked. Everything I’ve tried only changes when I close and reopen the view because it happens on appearance. Is there any way to make it change instantly? Thanks for any help!

Answered by robnotyou in 715367022

Try this:

import SwiftUI

struct ButtonTest: View {
    
    @State private var isOn = false
    var body: some View {
        Button {
            isOn.toggle()
        } label: {
            Image(systemName: isOn ? "star" : "star.fill")
        }
    }
}

struct ButtonTest_Previews: PreviewProvider {
    static var previews: some View {
        ButtonTest()
    }
}
Accepted Answer

Try this:

import SwiftUI

struct ButtonTest: View {
    
    @State private var isOn = false
    var body: some View {
        Button {
            isOn.toggle()
        } label: {
            Image(systemName: isOn ? "star" : "star.fill")
        }
    }
}

struct ButtonTest_Previews: PreviewProvider {
    static var previews: some View {
        ButtonTest()
    }
}
Button That Changes Label on Click
 
 
Q