SwiftUI - User Inputs

Continuing with the series on SwiftUI, today we will look into how to handle user inputs in SwiftUI.

In SwiftUI, the user inputs are generally stored in States. So before looking into user inputs and how to handle them let's understand States and Bindings.

States and Bindings

SwiftUI has inbuilt support for state management. It provides a property wrapper @State  to declare a property as a state variable. These states are stored in the application such that their values do not get lost when a view updates. Views are bound to state variable changes, i.e., they update themselves when the value of the variable changes.

A user generally interacts with the application using input components such as Buttons, Toggles, Text fields, etc. We will look at their implementations in SwiftUI.


TextField

TextField takes string inputs from the user such as name, email, passwords, etc. We can use a state variable to track the value which is entered in the text field. Look at the example below on how to use this component.

Toggle

The Toggle component is used to take a boolean input from the user. Its equivalent in UIKit is the UISwitch component. We can customize the tint colour. We can also add it as a button by setting the toggleStyle modifier.

Stepper

The Stepper lets the user input a value by tapping the plus and minus buttons. It is equivalent to UIStepper from UIKit. Configurations such as the step value and the range can be configured when the Component is initialized. It also provides callback such as onIncrement, onDecrement, and onEditingChanged.


In this article, we have discussed some of the components through which the user interacts with the application and how to handle the interactions in different SwiftUI Components.

Dhruv Tailor

Dhruv Tailor

Software Engineer developing mobile apps at PLG Works
Surat, Gujarat