Reputation: 8066
Hello I have some codes to create dynamic button as below:
- (void)viewDidLoad {
for (int i = 0; i < 9; i++)
for (int j = 0; j < 8; j++) {
forControlEvents:UIControlEventTouchDown];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(10+i*34 , 130+j*30, 30 , 20 );
[button setTitle:@"00" forState: UIControlStateNormal];
[button addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button.tag = i;
}
}
I hope to access one dynamic button with tag
How can I do
Welcome any comment.
Thanks interdev
Upvotes: 0
Views: 1373
Reputation: 5589
As rekle stated, your views will be assigned the same tag. Use his suggestion to assign the tag (i*100)+j
. Then to retrieve those views from another method in the same class, you can use [UIView viewWithTag:]
as follows:
for (int i = 0; i < 9; i++)
for (int j = 0; j < 8; j++) {
UIButton *button = [self.view viewWithTag:(i*100)+j];
// Do more stuff here...
}
}
Here are the Apple docs on viewWithTag.
Upvotes: 1
Reputation: 2375
Another problem you have is that you are setting every button created in the 'j' loop to the tag 'i'. This means you will 8 buttons with the same tag ID. You need to do something different with the tag based on the 'i' and 'j' indices. Maybe something like:
button.tag = (i*100)+j;
That way you can extract the 'i' and 'j' indices from the tag.
Upvotes: 1
Reputation: 46965
you have to have a check like the following:
if (button.tag == 1) {
.....do something
}
or a switch statement:
switch (button.tag)
{
case 1:
statements
break;
case 2:
statements
break;
//more case statements
default:
statements
break;
}
Upvotes: 0