在viewDidLoad中,我以编程方式创建了26个UILabel(字母表中每个字母一个),我将字母表中的字母放入每个标签中(第一个中的A,第二个中的B ......)。
后来我想找到一个特定的标签(比如,包含字母“F”的标签)。我知道我想要找到的字母及其在字母表中的索引(因此对于F,我知道它的索引是5,因为F是字母表中的第6个字母)
我怎样才能找到这个标签?
当然,我可以制作26个IBOutlets并参考它们,但这看起来很麻烦。
这是我创建标签的方式:
// 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];
}
有两种基本方法可以做到这一点:
只需在视图控制器中将NSMutableArray
作为ivar,然后在创建时添加标签。要找到F,请使用[myArray objectAtIndex:5]
。
创建标签时,请设置其标签([letterLabel setTag:i]
)。然后,当您想要检索它时,请使用[[self view] viewWithTag:5]
。
我能想到的两种方法:
NSArray
;tag
属性,并使用[self.view viewWithTag:TheTagForTheLabel];
访问它们我可能会创建一个带有NSString的NSMutableDictionary,其中包含字母作为键,关联的UILabel作为对象。