UILabel以编程方式创建-再次找到它吗? [英] UILabel created programmatically - find it again?
问题描述
在viewDidLoad中,我以编程方式创建了26个UILabel(一个字母针对每个字母),并将每个字母中的字母放入每个标签(第一个标签中的A,第二个标签中的B ...).
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...).
稍后,我想找到一个特定的标签(例如,包含字母"F"的标签).我知道我要查找的字母及其在字母表中的索引(因此对于F,我知道它的索引为5,因为F是字母表中的第六个字母)
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)
如何找到该标签?
当然,我可以制作26个IBOutlet并引用它们,但这似乎很麻烦.
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:
只需在视图控制器中将 NSMutableArray
设置为ivar,然后在创建标签时将其添加即可.要找到F,请使用 [myArray objectAtIndex:5]
.
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]
.
创建标签时,设置其标签( [letterLabel setTag:i]
).然后,当您要检索它时,请使用 [[[self view] viewWithTag:5]
.
When you create the label, set its tag ([letterLabel setTag:i]
). Then, when you want to retrieve it, use [[self view] viewWithTag:5]
.
这篇关于UILabel以编程方式创建-再次找到它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!