您可以使用以下代码验证字母字符串。
使用NSPredicate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return [self validateStringWithAlphabet:string];
}
- (BOOL)validateStringWithAlphabet:(NSString *)string {
NSString *stringRegex = @"[A-Za-z]";
NSPredicate *stringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringRegex];
return [stringPredicate evaluateWithObject:string];
}
使用NSCharacterSet
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField == yourTextField)
{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
return YES;
}