Binding & State of Variables in SwiftUI

All apps take some user inputs, display output by reflecting the correct changes and modifications. Suppose I have a login screen, until the user has entered the Username and Password I wont enable the Login button. Once the users satisfies this scenario I should reflect the change by enabling the Login Button.

struct ContentView: View {
    @State private var name = ""
    @State private var age = ""
    var body: some View {
        Form {
            Text("Personal Details Form")
                .font(.headline)
                .foregroundColor(.red)
            TextField("Name", text: $name)
            TextField("Age", text: $age)
            Text("Your Name - \(name)")
            Text("Your Age - \(age)")
        }
    }
}


So as to make this possible in SwiftUI we have to use @State attribute while declaration of a variable. So now SwiftUI will itself keep watch on any changes occurring with this variable and update the UI where it has been used.
Now you would ask why I have used that $ sign with these variables while using them with TextFields. It is because SwiftUI tries to refer to the actual data rather than the properties current value. Here $ is for Two Way Binding. It is required to show the data of the property here and write it back to the property.
In above code snippet I have two TextFields and two Texts (you can say Labels), now as user tries to enter name and age character by character the name and age will be reflected instantly to the Texts.
Give it a shot and you would find this very helpful.



Comments

Popular posts from this blog

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

payUmoney Payment Gateway Integration in iOS App (Objective C)

Check Internet Connectivity Using AFNetworking 2.0