2

I have tried to use the write a form, with a textfield that ask user to input the number. However, I found that it is always 0 even if the user has changed the number from 0 to another value, say 10

struct AddRecordView: View {

   @State private var age = 0
    var body: some View {
    Form {
       Section {
            HStack {
                Text("Age")
                Spacer()
                TextField("age", value: $age, formatter: NumberFormatter()).multilineTextAlignment(.trailing)
                    .keyboardType(.numberPad)
            }
        }
    }.toolbar {
      ToolbarItem(placement: .navigationBarTrailing) {
         Button("Add") {
            print("\(self.age)") // always 0 here?
      }
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
user6539552
  • 1,331
  • 2
  • 19
  • 39
  • Does this answer your question? [SwiftUI TextField with formatter not working?](https://stackoverflow.com/questions/56799456/swiftui-textfield-with-formatter-not-working) – aheze Apr 02 '21 at 15:52

1 Answers1

0

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 }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571