Skip to content

Instantly share code, notes, and snippets.

@soaringkonoha
Last active September 11, 2022 09:29
Show Gist options
  • Save soaringkonoha/752e348535a4b6f29bd064d3fbb36fd6 to your computer and use it in GitHub Desktop.
Save soaringkonoha/752e348535a4b6f29bd064d3fbb36fd6 to your computer and use it in GitHub Desktop.

State

A property wrapper type that can read and write a value managed by SwiftUI. https://developer.apple.com/documentation/swiftui/state

@State

In a View's struct, you can't change a value of properties directly, whereas a wrapped property using @State attribute can be changed its value by SwiftUI. State properties change, then SwiftUI re-renders the View that refers to these.

import SwiftUI

struct ContentView: View {
    @State private var isPowerOn = false
    
    var body: some View {
        Button(action: {
            isPowerOn.toggle()
        }) {
            Image(systemName: "power")
                .foregroundColor(isPowerOn ? .blue : .gray)
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment