UITextField 只能输入字母、数字的方法小结

实现下面的委托

#define NUMBERS @"0123456789 "

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;        
    if(textField == phoneNumberField)
    {
         //invertedSet 方法是去反字符,把所有的除了数字的字符都找出来        

        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];        

        //componentsSeparatedByCharactersInSet 方法是把输入框输入的字符string 根据cs中字符一个一个去除cs字符并分割成单字符并转化为 NSArray, 然后componentsJoinedByString 是把  NSArray的字符通过 ""无间隔连接成一个NSString字符 赋给filtered.就是只剩数字了.
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];        
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请输入数字" 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"确定" 
                                                  otherButtonTitles:nil];
            
            [alert show];
            [alert release];
            return NO;
        }    
    }

        //其他的类型不需要检测,直接写入
        return YES;        
}
如果输入的不是数字,进行提示。

原文地址:https://www.cnblogs.com/fjfhxotfl/p/3601362.html