Demasterpl Demasterpl - 5 months ago 79
iOS Question

Allow only Numbers for UITextField input

The iPad does not have a "Numpad" keyboard like the iPhone/iPod does.

I'm looking to find how I can restrict the user's keyboard to only accept values 0 through 9.

I would imagine using UITextField's "shouldChangeCharactersInRange" but I don't know the best way to implement it.

Answer

This may not be ideal, but this is how I handled the problem on a SSN verification field, you can modify the max length and remove the if statement checking for keyboard type if you need to.

There is also logic to suppress the max length alerts when the user is typing as opposed to pasting data.

In the context of this code, BasicAlert() is a #define macro that simply shows a UIAlertView using the title and message strings passed.

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the object that will contain this code, because otherwise it would never be called.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // allow backspace
    if (!string.length)
    {
        return YES;
    }

    // Prevent invalid character input, if keyboard is numberpad
    if (textField.keyboardType == UIKeyboardTypeNumberPad)
    {
        if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
        {
            // BasicAlert(@"", @"This field accepts only numeric entries.");
            return NO;
        }
    }

    // verify max length has not been exceeded
    NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (proposedText.length > 4) // 4 was chosen for SSN verification
    {
        // suppress the max length message only when the user is typing
        // easy: pasted data has a length greater than 1; who copy/pastes one character?
        if (string.length > 1)
        {
            // BasicAlert(@"", @"This field accepts a maximum of 4 characters.");
        }

        return NO;
    }

    // only enable the OK/submit button if they have entered all numbers for the last four of their SSN (prevents early submissions/trips to authentication server)
    self.answerButton.enabled = (proposedText.length == 4);

    return YES;
}