What is @State in SwiftUI ?
The @State
keyword is a @propertyWrapper
, a feature just recently introduced in Swift 5.1
- State is a value or a set of values, that can change over time, and that affects a view’s behaviour, content, or layout. You use property with the @State attribute to add a state to a view.
- when you initialize a property that's marked
@State
, you're not actually creating your own variable, but rather promptingSwiftUI
to create "something" in the background that stores what you set and monitors it from now on! Your@State var
just acts as a delegate to access this wrapper.
- Every time your
@State
variable is written,SwiftUI
will know as it is monitoring it. It will also know whether the@State
variable was read from theView
'sbody
. Using this information, it will be able to recompute anyView
having referenced a@State
variable in itsbody
after a change to this variable.
Code Example:-
import SwiftUI
struct ContentView: View {
@State var counter = 0
var body: some View {
print("ContentView")
return VStack {
Button("Tap me!") { self.counter += 1 }
LabelView(number: counter)
}
}
}
//Label created
struct LabelView: View {
let number: Int
var body: some View {
print("LabelView")
return Group {
Text("You've tapped \(number) times")
}
}
}
Comments
Post a Comment