tags:

views:

46

answers:

2

Hi, I've seen people using tags in iphone programming, like inside labels or tableview cells:

name.tag = kNameTag

Can someone explain with an example how these tags might be used? I gather that it's so that you can refer to a ui element later? Like if you programmatically use a for loop to create an array of UIButtons onto the iphone screen, do you assign tags to each button within the for loop or something?

Thanks!

+2  A: 

The example you've included in your question is one of the common ones.

You can instantiate buttons (or other UI elements) in a loop, assigning a incremental tag to each. When an IBAction is invoked by one of those buttons, you can ask the sender for it's tag, which tells you exactly which button triggered the request.

for( int i = 0; i < 10; i++ ) {
    UIButton * button = [[UIButton alloc] init...];
    button.tag = i;
}

IBAction:

- (IBAction)doSomethingFromButtonTap:(id)sender {
    NSLog(@"Button pressed: %d", [sender tag]);
}

They're also widely used to find specific subviews within a parent view. UIView provides a viewWithTag:(NSInteger)tag method. This is useful when building custom views without subclassing (or situations where you don't want to hold references to subviews, but know the tag).

dannywartnaby
+1  A: 
tc.