Monday, 29 August 2016

Allow only numbers in the UITextField - IOS Tutorial



Numeric Inoput UITextField IOS Tutorial


Introduction to how force UITextField to accept numeric values in ios:

Validations are important in IOS app development that includes user input. Sometimes we, need only
numeric values to be entered into the UITextField.
 In this post we will look at the code that helps us in achieving our requirement.

Code to force UITextField to only accept numeric values:

Below is the code snippet, that will make UItextField to only accept numeric input

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // For allowing backspace
    if (!string.length)
    {
        return YES;
    }
    
    // Only allows numbers to be entered in UITextField 
    if (textField.keyboardType == UIKeyboardTypeNumberPad)
    {
        if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
        {
            return NO;
        }
    }

    
    return YES;

}


The above method is a delegate method of UITextField and you have to set your UITextField to point to their delegates like below line of code

phoneNumber.delegate = self;





No comments:
Write comments