SwiftUI Sate and Binding

Whenever we have to build dynamic user interfaces in SwiftUI, managing data flow between views is crucial. Two key property wrappers — @State and @Binding


@State - It is a property wrapper type that allows reading and writing a value managed by SwiftUI. When the value of the State property changes, the SwiftUI framework updates the parts of the view hierarchy that depend on the value. 


  • The view itself owns the source of truth.
  • It allows SwiftUI to monitor changes and automatically re-render the view when the data updates.
  • It is initialized only once during the view life cycle.
  • It is defined as private property to prevent unwanted initialization.
  • It is defined by applying the @State attribute to a property declaration and providing an initial value, like below. 


@State private var count: Int = 0

Uses in practice


Struct ContentView: View {

    @State private var count: Int = 0


    var body: some View {

        VStack {

            Text("Tap count: \(count)")

            Button("count") {

                tapCount += 1

            }

        }

    }

}


@Binding - It is a property wrapper type that allows reading and writing a value managed by SwiftUI. When the value of the State property changes, the SwiftUI framework updates the parts of the view hierarchy that depend on the value. 



Post a Comment

0 Comments