Change the TextField values programmatically in SwiftUI
In this tutorial, we will see how to change the TextField values programmatically in SwiftUI.
In this article, we will cover the topics mentioned below.
- Programmatically Changing TextField Values
- Toggle Button for TextField Values
Now, explore the above-mentioned topics one by one to achieve this task.
Programmatically Changing TextField Values
We can change the value of a TextField programmatically by binding it to a @State or @Binding property. For this purpose, we need to have a @State variable that represents the text entered into the TextField.
Now, have a look at the example below.
import SwiftUI
struct ContentView: View {
@State private var textValue: String = "Initial Value"
var body: some View {
VStack(spacing: 20) {
TextField("Enter text", text: $textValue)
.font(.title2)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Change Text") {
// Change the textValue programmatically
textValue = "New Value"
}
.font(.title2)
}
.padding()
}
}In the above program, the TextField is bound to the textValue property using text: $textValue. So, if the value of textValue is changed elsewhere in the code, the TextField will be updated to show the new value.
When we press the button it will change the value of textValue to “New Value, which updates the TextField.
Output:

Toggle Button for TextField Values
Now, if we want a button that toggles between two different values for textValue each time when it is pressed. We can achieve this by using a conditional statement to check the current value of textValue and change it accordingly.
Example
import SwiftUI
struct ContentView: View {
@State private var textValue: String = "Initial Value"
@State private var isInitialValue: Bool = true
var body: some View {
VStack(spacing: 20) {
TextField("Enter text", text: $textValue)
.font(.title2)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Change Text") {
// Toggle between values based on the current state
if isInitialValue {
textValue = "New Value"
} else {
textValue = "Initial Value"
}
// Update the state
isInitialValue.toggle()
}
.font(.title2)
}
.padding()
}
}In the above program, I have declared a boolean @State property called isInitialValue and initialized it as true. This variable is used to determine which value to set for textValue when the button is pressed.
The button action will modify the textValue variable based on the current value of isInitialValue.
If the isInitialValue is true, it will set textValue to “New Value“, otherwise, it will set it to “Initial Value“.
Once the button is pressed and the textValue is updated based on the current state of isInitialValue, the code toggles the isInitialValue boolean. This ensures that the next press will switch to the opposite value.
Output:

You can also check out the link to Clear a TextField on button tap in SwiftUI
Leave a Reply