user2489946
user2489946

Reputation: 291

How to pass the tag of a uibutton on press

I want to pass the tag of a uibutton when it is pressed to a designated method, but when i try this, i receive an error message. Please help. Code:

   UIButton *deleteButton  = [[UIButton alloc]initWithFrame:CGRectMake(230, dateLabel.frame.origin.y, 70, 27)];
    [deleteButton addTarget:self action:@selector(deleteButtonPressed:i) forControlEvents:UIControlEventTouchDown];
    [deleteButton setBackgroundImage:[UIImage imageNamed:@"delete.jpg"] forState:UIControlStateNormal];
    [deleteButton setTag:i];

and then

    -(void)deleteButtonPressed:(int)tag
{
    NSLog(@"Button Pressed");
    NSLog(@"%i", tag);


}

Upvotes: 1

Views: 121

Answers (2)

rdelmar
rdelmar

Reputation: 104082

You can't pass an argument in an @selector. That should just be @selector(deleteButtonPressed:).

Then in the action method:

    -(void)deleteButtonPressed:(UIButton *) sender
{
    NSLog(@"Button Pressed");
    NSLog(@"%d", sender.tag);


}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Event handlers do not pass a tag by itself, they pass the entire button:

UIButton *deleteButton  = [[UIButton alloc]initWithFrame:CGRectMake(230, dateLabel.frame.origin.y, 70, 27)];
[deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchDown];
[deleteButton setBackgroundImage:[UIImage imageNamed:@"delete.jpg"] forState:UIControlStateNormal];
[deleteButton setTag:i];

Now you can get the tag from the button passed in like this:

-(void)deleteButtonPressed:(UIButton*)button {
    NSLog(@"Button Pressed, tag=%i", button.tag);
}

Upvotes: 1

Related Questions