I started today to use SwiftUI an I want to code a small calculator. Therefore I want a textfield where the user can write a number. But the usual textfields only accepts strings what can I do ?
Asked
Active
Viewed 126 times
0
-
Are you asking how to convert a string to Int? Because "usual textfields" accept numbers as well, just as a string, not int. You will need to convert the string to an int by `Int(myString)`, for example. – Cuneyt Nov 05 '20 at 21:57
-
Does this answer your question? [SwiftUI - How to create TextField that only accepts numbers](https://stackoverflow.com/questions/58733003/swiftui-how-to-create-textfield-that-only-accepts-numbers) – pawello2222 Nov 06 '20 at 00:01
2 Answers
0
If you want to force the TextField
keyboard to be numeric, just do this:
TextField("Input", text: $input)
.keyboardType(.decimalPad)
where the keyboardType
is a UIKeyboardType
.

NRitH
- 13,441
- 4
- 41
- 44
0
with SwiftUI 2.0 you could use something like this:
struct ContentView: View {
@State var theInt: Int?
@State var text = ""
var body: some View {
VStack {
TextField("enter a number", text: $text)
.onChange(of: text) {
let txt = $0.filter { "-0123456789".contains($0) }
if allowed(txt) {
theInt = Int(txt)
text = txt
} else {
text = String(txt.dropLast())
}
}
}
}
func allowed(_ str: String) -> Bool {
let num = str.starts(with: "-") ? String(str.dropFirst()) : str
return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: num))
}
}

workingdog support Ukraine
- 26,280
- 4
- 27
- 37