如何validationios中的多个文本字段

我正在处理包含多个TextFields的应用程序,有没有什么办法一次validation所有的字段,以确保它们在提交之前都不是空的,因为我能够逐一validation。

NSArray *viewsToRemove = [self.view subviews]; for (UIView *v in viewsToRemove) { if([v isKindOfClass:[UITextField class]]) { UITextField *txt=(UITextField *)v; //check for spaces NSString *str=[txt.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet if([str length]<=0) { //raise the error //To raise the proper error, check for the tag by assigning tag to each textfield in xib. } } } 

确保逻辑不会减慢你的应用程序。 否则一个接一个的validation…

如果使用storyboard / xib文件,则将所有文本字段连接到IBOutletCollection,而不是将每个文本字段连接到不同的IBOutlet。 IBOutletCollection提供了一个文本字段的数组,所以你可以使用枚举进行validation。

试试这个
在下面的代码中,你可以在你的视图中find所有的textfeild,然后检查它是否为空或零。

 - (IBAction)SubmitTapped:(id)sender { for (UIView *view in self.view.subviews) { if ([view isKindOfClass:[UITextField class]]) { UITextField *textField = (UITextField *)view; if([textField.text length]==0){ NSLog(@"Please fill..."); } } } } 

下面的代码片段为我工作:

  // Get the subviews of the view NSArray *listOfSubviews = [self.view subviews]; // Return if there are no subviews if ([listOfSubviews count] == 0) return; for (UIView *view in listOfSubviews) { if([view isKindOfClass:[UITextField class]]) { // Check for UITextField view UITextField *txtTextField = (UITextField *) view; if ((txtTextField.text.length != 0) || [txtTextField.text isEqualToString:@""]) { // textfield is empty } else { // textfield is not empty } } }