Instead of using a number formatter just use a Binding
to get and set your age value:
TextField("age", text: Binding(get: { String(age) }, set: { age = Int($0) ?? 0 }))
.keyboardType(.numberPad)
If you would like to accept only integers in your text field and limit the age range you would need to implement a text binding manager to control the text field content:
class TextBindingManager: ObservableObject {
@Published var string: String = ""
init(string: String) { self.string = string }
}
import SwiftUI
struct ContentView: View {
@ObservedObject private var bindingManager = TextBindingManager(string: "")
@State private var ageString = ""
@State private var age = 0
private let range = 1...123 // you can restrict the age range here
var body: some View {
NavigationView {
Form {
Section {
HStack {
Text("Age")
Spacer()
TextField("age", text: $bindingManager.string)
.keyboardType(.numberPad)
.onChange(of: bindingManager.string) { newValue in
guard !bindingManager.string.isEmpty else {
age = 0
return
}
bindingManager.string.removeAll(where: \.isDigit.negated)
guard let newValue = Int(bindingManager.string),
range ~= newValue
else {
if let digit = bindingManager.string.last?.wholeNumberValue {
age = digit
bindingManager.string = String(digit)
ageString = bindingManager.string
return
}
bindingManager.string = ageString
ageString = bindingManager.string
return
}
age = newValue
bindingManager.string = String(newValue)
ageString = bindingManager.string
}
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Add") {
print(age)
}
.disabled(!(range ~= age))
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension Character {
var isDigit: Bool { "0"..."9" ~= self }
}
extension Bool {
var negated: Bool { !self }
}