Allow only alphanumeric characters for a UITextField

前端 未结 7 973
野性不改
野性不改 2020-11-27 17:44

How would I go about allowing inputting only alphanumeric characters in an iOS UITextField?

7条回答
  •  旧时难觅i
    2020-11-27 18:21

    This is how I do it:

    // Define some constants:
    #define ALPHA                   @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    #define NUMERIC                 @"1234567890"
    #define ALPHA_NUMERIC           ALPHA NUMERIC
    
    // Make sure you are the text fields 'delegate', then this will get called before text gets changed.
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
        // This will be the character set of characters I do not want in my text field.  Then if the replacement string contains any of the characters, return NO so that the text does not change.
        NSCharacterSet *unacceptedInput = nil;
    
        // I have 4 types of textFields in my view, each one needs to deny a specific set of characters:
        if (textField == emailField) {
            //  Validating an email address doesnt work 100% yet, but I am working on it....  The rest work great!
            if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
                unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
            } else {
                unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
            }
        } else if (textField == phoneField) {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
        } else if (textField == fNameField || textField == lNameField) {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
        } else {
            unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
        }
    
        // If there are any characters that I do not want in the text field, return NO.
        return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
    }
    

    Check out the UITextFieldDelegate Reference too.

提交回复
热议问题