I'm developing an app for Ipad. I'm designing a forgot password screen to allow user to enter password to UITextField
. By design, the password only allow numeric input. I can set UITextFiled
keyboardtype
to be phonepad
in Iphone but the option seem not working for Ipad (Ipad always show the full keyboard layout). How can we achieve the keyboard for Ipad app that only have number?
Do I have to design my own keyboard layout? Any help is much appreciate. Thanks!
The keyboard type does not dictate what sort of input the textfield accepts, even if you use a custom keyboard that only displays numbers, the user can always paste something or use an external hardware keyboard.
To do that, you need to observe the input, for example, by becoming the UITextFieldDelegate and then:
Example in swift:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
// non decimal digit character set, better save this as a property instead of creating it for each keyboard stroke
let non_digits = NSCharacterSet.decimalDigits.inverted
// Find location for non digits
let range = string.rangeOfCharacter(from: non_digits)
if range == nil { // no non digits found, allow change
return true
}
return false // range was valid, meaning non digits were found
}
This will prevent any non digit character from being added to the textfield.