Using tags in iphone programming--can someone explain?
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 l开发者_Python百科oop or something?
Thanks!
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).
Tags are integers. You assign them to a view using UIView.tag. You then use -[UIView viewWithTag:]
to search the view hierarchy for the view.
UIKit doesn't use tags (I think), so they're free for you to use as necessary. However, tags are global to your app, so they're not an ideal replacement for IBOutlet (but it's often more convenient when you have a lot of views).
Avoid using 0 as a tag, since it's the default tag — [v viewWithTag:0]
is unlikely to return the view you're looking for.
精彩评论