UITextField - 将文本字段限制为某些字符

如果要对文本字段执行用户输入验证,请使用以下代码段:

// MARK: - UITextFieldDelegate

let allowedCharacters = CharacterSet(charactersIn:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz").inverted    

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    let components = string.components(separatedBy: allowedCharacters)
    let filtered = components.joined(separator: "")
    
    if string == filtered {
        
        return true

    } else {
        
        return false
    }
}

Objective-C

#define ACCEPTABLE_CHARACTERS @"0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  
{
      NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

      NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

      return [string isEqualToString:filtered];
}

此外,你还可以使用 apple 提供的字符集来执行验证:

请查看 https://developer.apple.com/reference/foundation/nscharacterset

let allowedCharacters = CharacterSet.alphanumerics.inverted
let allowedCharacters = CharacterSet.capitalizedLetters.inverted