同じコードを使用して、1 ~ 20 個のテキスト フィールドをビューに追加できるようにしたいと考えています。
私の考えは、for ループを使用し、毎回テキスト フィールドを追加して、最初のループで「textField1」を追加し、2 回目のループで「textField2」などを追加することです。
これをコーディングする方法がわからないので、あなたの助けを求めています。
同じコードを使用して、1 ~ 20 個のテキスト フィールドをビューに追加できるようにしたいと考えています。
私の考えは、for ループを使用し、毎回テキスト フィールドを追加して、最初のループで「textField1」を追加し、2 回目のループで「textField2」などを追加することです。
これをコーディングする方法がわからないので、あなたの助けを求めています。
このコードを試してください
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 three から値が必要な場合は、次のようにすることができます
UITextfield *textfield = (UITextfield *)[textFieldArray objectAtIndex:2];
NSLog(@"text of textField 3 is -- %@",textfield.text);
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];