如何验证ios中的多个文本字段

时间:2014-04-23 06:18:20

标签: ios

我正在处理包含多个TextFields的应用程序,有没有办法在提交之前立即验证所有字段以检查它们是否都是空的。我能够逐个验证。

4 个答案:

答案 0 :(得分:1)

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.
        }
    }
}

确保逻辑不会减慢您的应用程序。 否则一个接一个地验证...

答案 1 :(得分:1)

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

答案 2 :(得分:0)

试试这个 在下面的代码中,你可以在视图中找到所有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...");
            }
        }
    }
}

答案 3 :(得分:0)

以下代码段对我有用:

    // 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
            }
        }
    }
相关问题