Format TextField for numbers only in SwiftUI
In this tutorial, we will see how we can create a TextField that only accepts numbers as input in SwiftUI.
We can make a TextField accept only numbers by using the onChange() modifier. We can use the onChange() modifier with the TextField to filter out non-number input within the onChange closure.
Example
import SwiftUI
struct ContentView: View {
@State private var enteredNumber: String = ""
var body: some View {
TextField("Enter a number", text: $enteredNumber)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.onChange(of: enteredNumber) { newValue in
// Filter out non-number characters
self.enteredNumber = newValue.filter { "0123456789".contains($0) }
}
}
}In the above code, I have applied the .onChange() modifier to the TextField to observe changes in the enteredNumber.
Inside onChange, the newValue is filtered to allow only numbers. If the filtered value changes from the original input, it will update the enteredNumber to contain only the allowed numbers.
Output:

We can specify the type of keyboard that appears when we interact with a TextField. Simply we can apply the .keyboardType() modifier to the TextField and pass the .numberPad within this modifier to change the appearance of the keyboard.
Example
import SwiftUI
struct ContentView: View {
// State variable to store the entered number
@State private var enteredNumber: String = ""
var body: some View {
TextField("Enter a number", text: $enteredNumber)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
// Set the keyboard type to number pad
.keyboardType(.numberPad)
// Use onChange to monitor changes in the enteredNumber
.onChange(of: enteredNumber) { newValue in
// Filter out non-number characters from the entered text
self.enteredNumber = newValue.filter { "0123456789".contains($0) }
}
}
}In the above code, I have applied the .keyboardType(.numberPad) to the TextField to change the keyboard into a numeric keyboard. The keyboard will contain 0-9 digits and a backspace.
Output:

Leave a Reply