UITextField限制字符 (只为数字)

阅读更多

#define NUMBERS @"0123456789.\n"

 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;        
    if(textField == self.mTextField)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];        
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];        
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            return NO;
        }    
    }
    
    //其他的类型不需要检测,直接写入
    return YES;        
}

 

记得要设置代理哦~

你可能感兴趣的:(UITextField)