Search code examples
swiftuixcode11

How to change an @State var with a UIButton in SwiftUI


I tried to use a button to change the value of this @State variable using the code below. Even if it doesn't involve using a button, how would I change an @State var?(or any var type for SwiftUI)

import SwiftUI

struct SwiftUIView: View {

    @State var x = 0

    var body: some View {
        Button(action: //x = 1
) {
            Text("Button")
        }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

Solution

  • There is syntax error in your code. you missed to write closure for Button

    struct SwiftUIView: View {
        @State var x = 0
        var body: some View {
            Button(action: {
               self.x = 1
            }) {
               Text("Button")
            }
        }
    }