Limit number of characters entered into texfield

A common scenario in iOS development is to create a textfield that will only allow a certain number of characters to be entered. This often crops up in the form of PIN codes or password entry fields.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL validCharactersInRange = YES;

    if (![string isEqualToString:@""]) 
    {
        NSUInteger testLength = textField.text.length + string.length + range.length;
        validCharactersInRange = (testLength > 1) ? NO : YES; //change the 1 to your textfield's upper limit
    }

    return validCharactersInRange;
}