Lê Khánh Vinh
Lê Khánh Vinh

Reputation: 2611

UItextField restrict user to enter number only IOS app on ipad

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!

Upvotes: 1

Views: 1374

Answers (3)

Mohsin Khubaib Ahmed
Mohsin Khubaib Ahmed

Reputation: 1018

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
}

Upvotes: 0

Muhammad Usman Piracha
Muhammad Usman Piracha

Reputation: 199

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

Upvotes: 1

Moshe Gottlieb
Moshe Gottlieb

Reputation: 4023

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.

Upvotes: 3

Related Questions