Home > AI > IOS > SwiftUI >

@State

SwiftUI uses the @State property wrapper to allow us to modify values inside a struct, which would normally not be allowed because structs are value types. When we put @State before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI. This means SwiftUI can destroy and recreate our struct whenever needed (and this can happen a lot!), without losing the state it was storing.

To re-enforce the local nature of @State properties, Apple recommends you mark them as private, like this:

@State private var isFlagged: Bool = false

Example 1: @State and Toggle

struct ContentView: View {
    @State private var show: Bool = false

    
    var body: some View {
        VStack {
            Toggle(isOn: $show, label: {
                Text("Label")
            }).padding()
            if show {
                Text("good")
            }
        }
    }
}

Example 2: @State and .onTapGesture

struct ContentView: View {
    @State private var isFlipped = false

    var body: some View {
        VStack {
            if isFlipped {
                Circle()
                    .fill(Color.red)
                    .frame(width: 44, height: 44)
                Text("Taylor Swift – 1989")
                    .font(.headline)
            } else {
                Text("Taylor Swift – 1989")
                    .font(.headline)
                Circle()
                    .fill(Color.blue)
                    .frame(width: 44, height: 44)
            }
        }
        .onTapGesture {
            withAnimation {
                self.isFlipped.toggle()
            }
        }
    }
}

Leave a Reply