I want to create some UIbutton dynamically. And display the tag number. So I successfully made the buttons, I clicked the first button and it shown “null” for the tag, then I click the second button then the program crashed. I am not sure which part of my code went wrong.
Here is my code:
NSMutableArray *buttonsArray = [[NSMutableArray alloc] initWithObjects:nil];
for(int i = 0; i < [someArray count]; i++)
{
button = [[UIButton alloc] initWithFrame:CGRectMake(btnX,btnY,btnW,btnH)];
button.tag = i;
[buttonsArray addObject:button];
[[buttonsArray objectAtIndex:i] addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.text = [NSString stringWithFormat:@"Click it"];
[self.view addSubview:button];
btnY = btnY + 120;
}
-(IBAction) buttonPressed:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(@"%@", btn.tag);
}
That’s because
tagis anNSIntegerand you’re doingYou must use
%ldas the format specifier. Do