Reputation: 796
I have a loop that generates 100 textfields 10x10.
int counter=0;
for (int i = 0; i < 10; i++)
{
for (int ii = 0; ii < 10; ii++)
{
counter++;
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(0 + 25 * i ,60+25*ii,25,25)];
counter++;
tf.tag =counter;
[self.view addSubview:tf];
}
}
This is what I get:
1.Tags representation
1 11 21 31 41 51 61 71 81 91
2 12 22 32 42 52 62 72 82 92
3 …………
2.This is what I want:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21………..
Any ideas? Thank you!
Upvotes: 2
Views: 662
Reputation: 917
Another possibility:
int row = 0;
int column = 0;
for (int i = 0; i < 100; i++) {
if (!(i % 10) && i) {
row++;
column = 0;
}
CGRect newRect = CGRectMake(25.0 * column, 60.0 + 25.0 * row, 25.0, 25.0);
UITextField *tf = [[UITextField alloc] initWithFrame:newRect];
tf.tag = i;
[self.view addSubview:tf];
column++;
}
Upvotes: 0
Reputation: 24248
for (int i = 0; i < 10; i++)
{
for (int ii = 0; ii < 10; ii++)
{
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(0 + 25 * ii,60+25*i, 25, 25)];
tf.tag = ii + i * 10 + 1;
[self.view addSubview:tf];
}
}
Upvotes: 1
Reputation: 26036
So, forget about counter
. You can retrieve it with you i
and ii
.
Let's see what your 2 for
loop do, where a "-" mean nothing yet, and a "•" a UITextField
is put.
----------
----------
----------
Then:
•---------
----------
----------
Then:
•---------
•---------
----------
etc.
So we quickly see that i
represents a column and ii
a line. It would be good to rename them like this.
Now, if you had logged i
and ii
you could have figured out what was the logic, which is:
[tf setTag:(ii*10+i+1)];
Note that's just a kindly advice (not a "you could have done it alone if you did the debug yourself") to log things sometimes (like the counter: i
or ii
in our case) to understand them, especially in loops, when it can get tricky. I do that often when my loops don't do what I expect.
Upvotes: 2