UILabel created programmatically - find it again?
In viewDidLoad I have created 26 UILabels programmatically (one for each letter in the alphabet) and I have put the letters from the alphabet into each label (A in the first, B in the second...).
Later I would like to find one specific label (say, the label containing the letter "F"). I know both the letter I want to find and its index in the alphabet (so for F, I know that its index is 5 because F is the 6th letter in the alphabet)
How can I find this label?
Of course, I can make 26 IBOutlets and refer to them but this seems such a hassle.
This is how I create the labels:
// set letters
letters = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];
int positionX = 0;
int positionY = 0;
for(int i = 0; i < [letters count]; i++) {
/* a lot of positioning stuff is here (positionX and positionY is set. I have removed this to make the code look cleaner */
UILabel *letterLabel = [[UILabel alloc] initWithFrame:CGRectMake(positionX, positionY, 50, 50)];
letterLabel.text = [letters objectAtIndex:i];
letterLabel.backgroundColor = [UIColor clearColor];
letterLabel.font = [UIFont fontWithName:@"Helvetica" size开发者_运维问答:45];
letterLabel.textAlignment = UITextAlignmentCenter;
[self.view addSubview:letterLabel];
[letterLabel release];
}
There are two basic ways to do this:
1. Create An Array
Simply make an NSMutableArray
as an ivar in your view controller, then add the labels as they’re created. To find F, use [myArray objectAtIndex:5]
.
2. Use Tags
When you create the label, set its tag ([letterLabel setTag:i]
). Then, when you want to retrieve it, use [[self view] viewWithTag:5]
.
Two approaches I can think of:
Add all your labels to an
NSArray
;Set the
tag
property for all the labels with a specific know value for each label and access them with[self.view viewWithTag:TheTagForTheLabel];
I probably would've created an NSMutableDictionary with an NSString containing the letter as the key and the associated UILabel as the object.
精彩评论