在uitableview的多个UITextField中添加不同类型的验证

问题描述:

在我的uitableview行中使用多个uitextfield。在uitableview的多个UITextField中添加不同类型的验证

例如,用户可以在这两个uitextfield中键入数字范围。

现在我该如何处理这些uitextfield中输入值的验证?

例如uitextfield1不应该是低1和uitextfield2不应该是李建华,伍妍大于100

这是我的旧代码来设置文本字段具有唯一的数值:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

     NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet]; 

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

     return [string isEqualToString:filtered]; 

    return YES; 
} 

在我的cellForRowAtIndexPath

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
UITextField * UTX1 = (UITextField *)[cell viewWithTag:1]; 
UITextField * UTX2 = (UITextField *)[cell viewWithTag:2]; 
UTX1.delegate = self; 
UTX2.delegate = self; 
+0

如果您只想在文本字段中输入数值,那么为该文本字段设置数字小键盘,只允许数字值,不需要以编程方式检查。 – Yuvrajsinh 2014-10-29 05:35:03

+1

@Yuvrajsinh不好的建议。用户可以使用外部键盘或复制和粘贴。永远不要依赖键盘类型。 – rmaddy 2014-10-29 05:35:50

+0

@rmaddy在这种情况下的良好捕获必须以编程方式进行检查。 – Yuvrajsinh 2014-10-29 05:37:47

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
     // allow backspace 
     if (!string.length) 
     { 
      return YES; 
     } 

     // allow digit 0 to 9 
     if ([string intValue]) 
     { 
      if(textfield.tag==1){ // First textfield 
       if([string intValue]<1){ 
         return NO; 
       } 
      } 
      else if(textfield.tag==2){ // Second textfield 
       if([string intValue]>100){ 
         return NO; 
       } 
      } 
      return YES; 
     } 
     return NO; 
} 

您可以更改条件的数值范围,以允许每个文本框,按您的需要。

根据标记验证文本字段。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

     NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet]; 

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

if(textField.tag == 1) 
{ 
return [string isEqualToString:filtered] && [string intValue]> 1 ; 
} 
if(textfield.tag == 2) 
{ 
return [string isEqualToString:filtered] && [string intValue] < 100; 
} 
    return YES; 
}