UILabel以编程方式创建 - 再次找到它?

问题描述 投票:1回答:3

在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];
}
iphone sdk uilabel
3个回答
7
投票

有两种基本方法可以做到这一点:

1. Create An Array

只需在视图控制器中将NSMutableArray作为ivar,然后在创建时添加标签。要找到F,请使用[myArray objectAtIndex:5]

2. Use Tags

创建标签时,请设置其标签([letterLabel setTag:i])。然后,当您想要检索它时,请使用[[self view] viewWithTag:5]


4
投票

我能想到的两种方法:

  1. 将所有标签添加到NSArray;
  2. 为每个标签设置具有特定已知值的所有标签的tag属性,并使用[self.view viewWithTag:TheTagForTheLabel];访问它们

1
投票

我可能会创建一个带有NSString的NSMutableDictionary,其中包含字母作为键,关联的UILabel作为对象。

© www.soinside.com 2019 - 2024. All rights reserved.