You can filter what is typed, with TextField delegate. Don't forget to declare the ViewController as the delegate for the TextFields.
Can be improved if you want to allow to move insertion cursor in an existing text..
let gcTabAscii = 9
let gcLineFeedAscii = 10
let gcReturnAscii = 13
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let charCode = string.first?.asciiValue else {
if string == "" { // Accept backspace
return true
}
return false
}
if charCode == gcLineFeedAscii || charCode == gcReturnAscii { // It is lineFeed even when typing return
return true
}
if charCode == gcTabAscii { // Tab
textField.text = textField.text!
return false // You should fine tune here to allow for - sign or dot sign at start
}
let newString = textField.text! + string
if Int(newString) != nil { // So we typed something in newString and it is a valid number ; if you do not expect an Int but any number, test for Float(newString)
return true
} else {
return false // You could allow for - or starting dot with
// return newString == "-" || newString == "."
}
}
Topic:
Developer Tools & Services
SubTopic:
Xcode