When I have typed a few characters in the textfield and then the new character that has been added has been deleted from it, it is sent to the server and the entire amount that has been added is sent and is deleted without deleting the textfield and the value and prompt are dynamic so that I am not able to find out, I am getting only digit and only one point.
TextField("", text: Binding(
get: { userMeasurements[index.id].stringValue },
set: { newValue in
var updatedValue = newValue
updatedValue = updatedValue.filter { ".0123456789".contains($0) }
userMeasurements[index.id] = JSON(newValue)
let measurement = Measurement(measurement: index.id, value: newValue.filter { ".0123456789".contains($0) })
if !modifiedMeasurements.contains(measurement) {
modifiedMeasurements.append(measurement)
}
}), prompt: Text(index.desc).font(Font.custom("Agency FB", size: 16))
.foregroundColor(Constants.LightWhite))
.digitswithPointOnly(text: Binding<String>(
get: { userMeasurements[index.id].stringValue },
set: { newValue in
userMeasurements[index.id] = JSON(newValue)
let measurement = Measurement(measurement: index.id, value: newValue)
}
))
And this is my extension for decimal value
extension TextField where Label == Text {
func digitswithPointOnly(text: Binding<String>) -> some View {
self.keyboardType(.decimalPad)
.onChange(of: text.wrappedValue) { newValue in
var filtered = newValue.filter { "0123456789.".contains($0) }
let decimalCount = filtered.reduce(0) { $0 + ($1 == "." ? 1 : 0) }
if decimalCount > 1 {
filtered.removeLast()
} else if let index = filtered.firstIndex(of: ".") {let fractionalPart = filtered[filtered.index(after: index)...]
}
if filtered != text.wrappedValue {
text.wrappedValue = filtered
}
}
}
}
I am using xcode 14 for ios 17 and design for iPad