使用相同的代码添加多个文本字段

时间:2013-09-15 08:36:06

标签: ios

我希望能够使用相同的代码在我的视图中添加1到20个文本字段。

我的想法是使用for循环,每次添加一个文本字段,所以第一次循环时添加“textField1”,第二次添加“textField2”等。

我不确定如何编码,所以我正在寻找你的帮助。

3 个答案:

答案 0 :(得分:1)

for (int i = 0; i < 20; i++)
{
    UITextField *textField = //setup field
    textField.tag = i;
    [self.view addSubview:textField];
}

然后当你想稍后引用某个字段时

UITextField *textField6 = [self.view viewWithTag:6];
UITextField *textField18 = [self.view viewWithTag:18];
etc

答案 1 :(得分:1)

试试此代码

对于20个文本字段,您需要在UIScrollView中使用它们...您可以这样做 -

UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,460)];

[scrollView setDelegate:self];

//initialize a textfield array;

NSMutableArray *textFieldArray = [[NSMutableArray alloc]init];

//x, y for first textfield in UIScrollView

float x = 20;

float y = 20;

For(int i=1;i<21;i++)
{
   UITextfield *textField = [[UITextfield alloc]initWithFrame:CGRectMake(x,y,200,30)];
   textfield.tag = i;
   [textField setDelegate:self];

   //Add Textfield to array just for futureRefrence

   [textFieldArray addObject:textField];

   //Add textfield in UIScrollView

   [scrollView addSubview:textField];

   //Now iterate Y , So they won't over each other

   y = y+50;

}

//Now set ScrollView ContentSize 

[scrollView setContentSize:CGSizeMake:(320,20*y)];

//Now Finally Add ScrollView in UIView

[self.view addSubView:scrollView];

还记得在.h文件中声明委托。 并且您可以通过放入它们的数组访问这些文本字段,例如

如果你想要textfield三的值,你可以这样做

UITextfield *textfield = (UITextfield *)[textFieldArray objectAtIndex:2];
NSLog(@"text of textField 3 is -- %@",textfield.text);

答案 2 :(得分:1)

NSMutableArray* tfArray = [[NSMutableArray alloc]init];


for (int i = 0; i < 20; i++)
{
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];

    [self.view addSubview:textField];
    [tfArray addObject:textField];

}

如果你想引用一个字段:

第6个文本字段例如:(UITextField*)tfArray[5];