Open
Description
Description
Using a SwiftUI TextField with the selection property causes a crash when I type numbers, move the cursor to the middle, and continue typing. The error is: String index is out of bounds
Reproduction
struct ios18: View {
@State var goal: Int = 0
@State private var goalString: String = ""
private let numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.usesGroupingSeparator = true
return formatter
}()
@State private var selection: TextSelection? = nil
var body: some View {
TextField("Enter something", text: $goalString, selection: $selection)
.keyboardType(.decimalPad)
.onChange(of: goalString) { _ in
goalString = goalString.filter { $0.isNumber }
goal = Int(goalString) ?? 0
goalString = numberFormatter.string(for: goal) ?? "0"
}
}
}
Stack dump
struct ios18: View {
@State var goal: Int = 0
@State private var goalString: String = ""
private let numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.usesGroupingSeparator = true
return formatter
}()
@State private var selection: TextSelection? = nil
var body: some View {
TextField("Enter something", text: $goalString, selection: $selection)
.keyboardType(.decimalPad)
.onChange(of: goalString) { _ in
goalString = goalString.filter { $0.isNumber }
goal = Int(goalString) ?? 0
goalString = numberFormatter.string(for: goal) ?? "0"
}
}
}
Expected behavior
Not getting crash.
Environment
On debug environment