2014-10-29 63 views
0

在我的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

回答

1
- (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; 
} 

您可以更改條件的數值範圍,以允許每個文本框,按您的需要。

1

根據標記驗證文本字段。

- (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; 
}