kevin
kevin

Reputation: 129

UIbutton and actions problem

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);

}

Upvotes: 1

Views: 181

Answers (2)

user857280
user857280

Reputation: 25

Change the code as NSLog(@"%@",self.but.tag); or NSLog(@"%@",self.but.tag.me)

Upvotes: 0

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

That's because tag is an NSInteger and you're doing

NSLog(@"%@", btn.tag);

You must use %ld as the format specifier. Do

NSLog(@"%ld", btn.tag);

Upvotes: 1

Related Questions