如何访问textField Value,它是使用for循环在Objective C中动态创建的?

时间:2017-03-31 05:42:44

标签: objective-c

我在Objective C中使用for循环创建了4 UITextField。现在我想验证这些文本。这些文本字段是否为空。

 for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}

3 个答案:

答案 0 :(得分:0)

您可以使用标记值检索下面的文本字段。

endl

同样检查您是否可以申请其他文本字段。

注意:  确保您有唯一的标记值而不是0,1,2,3,4,5。

答案 1 :(得分:0)

如果您想检查UITextField是否为空,请定义macro以修剪空格。

#define TRIM(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

在按钮操作方法中。

UITextField *textField1 = [self.view viewWithTag:0];
UITextField *textField2 = [self.view viewWithTag:1];
UITextField *textField3 = [self.view viewWithTag:2];
UITextField *textField4 = [self.view viewWithTag:3];

if(![TRIM(textField1.text) length])
{
   // Your textfield is empty 
}
//Similarly check for other textfields

答案 2 :(得分:0)

for(int i=0;i<4; i++) {
    UITextField   *textField = [self.view viewWithTag:i];
    if (textField.hasText) {
        //If this returns true then text field has text otherwise not
    }
}

这将自动管理空格。