tags:

views:

449

answers:

2
Q: 

sender tag

I have a UIImageView object that when clicked it will play a animation, I want to reuse the same code to make multiple objects. How do I set the sender tag so it knows its a different object?

- (IBAction)startClick:(id)sender;

- (IBAction)startClick:(id)sender

{ //UIImageView *theButton = (UIImageView *)sender.tag;

bubble.animationImages = [NSArray arrayWithObjects:
                       [UIImage imageNamed: @"Pop_1.png"],
                       [UIImage imageNamed: @"Pop_2.png"],
                       [UIImage imageNamed: @"Pop_3.png"], nil];

[bubble setAnimationRepeatCount:1];
bubble.animationDuration = 1;
[bubble startAnimating];

}

+1  A: 

The sender is the object that called the startClick method. You can cast that object into a UIImageView and then look at that object's tag property to determine which one it is.

You'll need to set the tag property elsewhere in the code. If you have the UIImageViews in Interface Builder, you can use the properties window to enter a tag number. Otherwise, when you allocate and init your UIImageViews, set the tag property then.

Ken Pespisa
+1  A: 

Use [sender tag].

Why not sender.tag, you ask?

You can only use the dot notation if you cast sender as an instance of UIView, as in ((UIView *)sender).tag. Objects of UIView have a tag property. If you don't cast sender as an instance of UIView, it is just an id that conforms to the NSURLAuthenticationChallengeSender protocol, and it lacks a tag property.

Here's an example of using a button's tag:

#define kButtonTag  2

- (void)viewDidLoad {
   // ... view setup ...

   UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
   // ... button setup ...

   button.tag = kButtonTag;

   [super viewDidLoad];
}

- (IBAction)startClicked:(id)sender {

   if ([sender tag] == kButtonTag) {
        // do something
    }
}
Rose Perrone