2

I want to create dynamic UITextField with different object name.I have shown the code below for creating textfield dynamically. How can i create each textfield with different object name ?

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

        CGRect txtFldFrame;
        if (x==0) 
            txtFldFrame=CGRectMake(385, 620, 278, 45);
        else
            txtFldFrame=CGRectMake(385, txtFldFrame.origin.y+60, 278, 45);
        [self createTxtImg:txtImgFrame createTextfield:txtFldFrame];
    }

In the createTextfield:(CGRect )txtfldframe {

   UITextField *txtFld1=[[UITextField alloc]init];
txtFld1.frame=txtfldframe;
[txtFld1 setTag:textChk];
txtFld1.borderStyle = UITextBorderStyleNone;
txtFld1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtFld1.textAlignment=UITextAlignmentLeft;
txtFld1.textColor=[UIColor colorWithRed:17/255.0 green:61/255.0 blue:83/255.0 alpha:1];
txtFld1.font = [UIFont systemFontOfSize:22];
txtFld1.backgroundColor = [UIColor clearColor];
txtFld1.autocorrectionType = UITextAutocorrectionTypeNo;
txtFld1.returnKeyType = UIReturnKeyDone;
txtFld1.clearButtonMode = UITextFieldViewModeWhileEditing;
txtFld1.autocapitalizationType=UITextAutocapitalizationTypeNone;
txtFld1.delegate = self;
[subScrollView addSubview:txtFld1];

}

4

3 回答 3

6

绝对没有理由创建具有不同(唯一名称)的文本字段。我很确定您想要唯一名称的原因是您可以稍后在代码中访问它们并编辑它们的值,但诀窍是:使用唯一的标签号。

这是一个例子:

for (int i=0; i<4; i++) {
    UITextField *myTextfield = [[UITextField alloc] initWithFrame:CGRectZero];
    myTextField.tag = 200+i;
    [self.view addSubview:myTextField];
}

现在我们创建了 4 个文本字段,标签分别为 200、201、202 和 203

例如,稍后在代码中,当我们想要引用第二个文本字段时,我们所要做的就是:

UITextField *myTextField = (UITextField *)[self.view viewWithTag:201];

现在我们有了控制权,我们可以获取或设置任何东西......

作为预防措施,我建议您检查您是否确实获得了 UI 元素,方法是使用:

if (!myTextField)
   return;
于 2012-07-24T14:07:00.387 回答
0

我不明白一切,因为你没有提供太多信息。

如果要初始化多个 UITextField:

UITextField *myTextField1 = [[UITextField alloc] init];  
UITextField *myTextField2 = [[UITextField alloc] init];  
UITextField *myTextField2 = [[UITextField alloc] init];

等等...

如果您想随机或循环执行此操作,我建议循环并将对象放入带有随机键的字典中,如下所示:

NSMutableDictionary *myDict = [NSMutableDictionary dictionary];
for (int i=0; i<20; i++) {
    UITextField *myTextfield = [[UITextField alloc] initWithFrame:CGRectZero];
    [myDict setObject:myTextfield forKey:[NSString stringWithFormat:@"myTextfield%d", i]];
    [myTextfield release];
}

NSLog(@"Dict: %@",myDict);
于 2012-07-24T11:41:02.533 回答
0

使用以下代码创建文本框:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(150, 12, 120, 25)];
[self.view addSubview:textField];

对于另一个文本框,只需更改对象名称 (textField)

于 2012-07-24T11:16:38.410 回答