SwiftUI TextField with formatter not working?

前端 未结 5 1895
走了就别回头了
走了就别回头了 2020-11-29 02:00

I\'m trying to get a numeric field updated so I\'m using a TextField with the formatter: parameter set. It formats the number into the entry field just fine, but does not up

5条回答
  •  死守一世寂寞
    2020-11-29 02:20

    Plan B. Since using value: and NumberFormatter doesn’t work, we can use a customised TextField. I have wrapped the TextField inside a struct, so that you can use it as transparently as possible.

    I am very new to both Swift and SwiftUI, so there is no doubt a more elegant solution.

    struct IntField: View {
        @Binding var int: Int
        @State private var intString: String  = ""
        var body: some View {
            return TextField("", text: $intString)
            .onReceive(Just(intString)) { value in
                if let i = Int(value) { int = i }
                else { intString = "\(int)" }
            }
            .onAppear(perform: {
                intString = "\(int)"
            })
        }
    }
    

    and in the ContentView:

    struct ContentView: View {
        @State var testInt: Int = 0
        var body: some View {
            return HStack {
                Text("Number:")
                IntField(int: $testInt);
                Text("Value: \(testInt)")
            }
        }
    }
    

    Basically, we work with a TextField("…", text: …), which behaves as desired, and use a proxy text field.

    Unlike the version using value: and NumberFormatter, the .onReceive method responds immeditately, and we use it to set the real integer value, which is bound. While we’re at it, we check whether the text really yields an integer.

    The .onAppear method is used to fill the string from the integer.

    You can do the same with FloatField.

    This might do the job until Apple finishes the job.

提交回复
热议问题