1

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!

Lê Khánh Vinh
  • 2,591
  • 5
  • 31
  • 77

3 Answers3

3

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.

Moshe Gottlieb
  • 3,963
  • 25
  • 41
  • Thanks for your help. For the layout of the keyboard in ipad app. Can we change the default layout (the one with all character, number symbol...)? – Lê Khánh Vinh Sep 22 '16 at 15:12
  • @LêKhánhVinh there's no decimal layout for the iPad like there is for the iPhone, I saw many apps that use a PIN code draw their own keypad for this purpose. – Moshe Gottlieb Sep 22 '16 at 15:14
  • Do you know any library or example so that we can follow to achieve the numeric keyboard for ipad app? – Lê Khánh Vinh Sep 22 '16 at 15:18
  • @LêKhánhVinh See [this question](http://stackoverflow.com/questions/27409483/number-keyboard-in-ipad) for some options, never tried it. – Moshe Gottlieb Sep 22 '16 at 15:22
1

There is not a built in number-only (phone/pin) keyboard on iPad You need to implement your own keyboard if you want this on iPad.

There are many examples out there:

https://github.com/azu/NumericKeypad

https://github.com/lnafziger/Numberpad

https://github.com/benzado/HSNumericField

0

Yes I was facing the same for iPad hence I used this:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // to avoid any other characters except digits
    return string.rangeOfCharacter(from: CharacterSet(charactersIn:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-=_+`~[{]}|\\: ;\"/?>.<,'")) == nil
}
Mohsin Khubaib Ahmed
  • 1,008
  • 16
  • 32