Chris
Chris

Reputation: 7310

Objective C: Using tags

I've been researching for the past few days and can't figure this out. I have a lot of buttons that do the same thing (disappear when clicked). I define each one with its own tag, but how do I determine which one is pressed?

-(IBAction) tapBrick{
int x = brick.tag;
NSLog(@"%d", x);


//remove last brick
[brick removeFromSuperview];

//add to score
count++;
NSString *scoreString = [NSString stringWithFormat:@"%d", count];
score.text = scoreString;

//determine x y coordinates
int xPos, yPos;
xPos = arc4random() % 250;
yPos = arc4random() % 370;
}


-(void) produceBricks {
//determine x y coordinates
int xPos, yPos;
xPos = arc4random() % 250;
yPos = arc4random() % 370;

//create brick
brick = [[UIButton alloc] initWithFrame:CGRectMake(xPos,yPos + 60,70,30)];  
[brick setBackgroundColor:[UIColor blackColor]];
[brick setTag:i];
[brick addTarget:self action:@selector(tapBrick) forControlEvents:UIControlEventTouchUpInside];
i++;
[self.view addSubview:brick];


}

Produce Bricks is called every 2 seconds by a timer.

Upvotes: 0

Views: 10695

Answers (1)

Sam Ritchie
Sam Ritchie

Reputation: 11038

Chris, if all you need to do is identify the button that's been pressed, simply change your method declaration to accept a sender parameter, and the caller (a UIButton, in this case) will supply a reference to itself. Create a UIButton pointer, and you'll be able to access the tag of the pressed button.

-(void) tapBrick:(id)sender {
    //this is the button that called your method.
    UIButton *theButton = (UIButton *)sender;

    int tag = theButton.tag;
    NSLog(@"%d", tag);

    [theButton removeFromSuperview];

    //rest of code  
}

(By the way, since you're creating the buttons with code, you don't need to declare a return value of IBAction. IBAction is the same as void, except that it tips off Interface Builder that you'll be connecting some IBOutlet to that particular method.)

Upvotes: 5

Related Questions