Allow only numbers in the UITextField – IOS Tutorial

Allow only numbers in the  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 to allow only numbers in UITextField, thus user will not be able to enter other character apart from numbers.

Code to allow 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;