在objective-c中动态创建可访问的UILabel

时间:2011-04-16 07:15:17

标签: iphone objective-c

我正在尝试为objective-c中的单词中的每个字母动态创建UILabel。正如你所看到的,我传递了将用于单词的字母数量,我需要填写下面的注释部分:

-(void)createWordLabels:(int)numberOfLetters
{
    //create a set of word labels
    int i = 0;
    for(i = 0; i < numberOfLetters; i++)
    {
        //create a set of labels for each of the letters -> connect them to variables
    }
}

需要更改标签。如果我想从A改变一个字母 - > B,那么我希望能够动态地做到这一点。这里有任何帮助。

现在这就是我所拥有的,但是,我希望能够将这组标签集中在屏幕中间:

    -(void)createWordLabels:(int)wordSize
{
    int width = 0;
    //create a set of word labels
    int i = 0;
    for(i = 0; i < wordSize; i++)
    {
        //TO DO: create a set of labels for each of the letters -> connect them to variables
        UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 + width, 150, 30, 50)];
        [newLabel setText:@"-"];
        newLabel.textAlignment = UITextAlignmentCenter;
        [self.view addSubview:newLabel];
        [newLabel release];
        width += 30;
    }
}

2 个答案:

答案 0 :(得分:5)

为每个UILabels设置标记值

e.g。

#define LABEL_TAG 1000

-(void)createWordLabels:(int)numberOfLetters
{
    //create a set of word labels
    int i = 0;
    for(i = 0; i < numberOfLetters; i++)
    {
        //create a set of labels for each of the letters -> connect them to variables
        UILabel *label = [[UILabel......
        [label setTag:LABEL_TAG+i];
        [self addSubview:label];
        ......
    }
}

然后访问标签10位置,例如

UILabel *label = (UILabel*)[self viewWithTag:LABEL_TAG+10];

答案 1 :(得分:3)

- (void)viewDidLoad
{
    [super viewDidLoad];

    for (int i=0; i<10; i++) 
    {
//For printing the text using for loop we change the cordinates every time for example see the "y=(i*20) like this we change x also so every time when loop run,the statement will print in different location"   

//This is use for adding dynamic label and also the last line must be written in the same scope. 

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,(i*40), 100, 100)];

    //titleLabel = titleLabel;
    //[titleLabel release];

    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont italicSystemFontOfSize:20];
    titleLabel.numberOfLines = 5;
    titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    titleLabel.text = @"mihir patel";

//Calculate the expected size based on the font and linebreak mode of label
    CGSize maximumLabelSize = CGSizeMake(300,400);
    CGSize expectedLabelSize = [@"mihir" sizeWithFont:titleLabel.font constrainedToSize:maximumLabelSize lineBreakMode:titleLabel.lineBreakMode];
//Adjust the label the the new height
    CGRect newFrame = titleLabel.frame;
    newFrame.size.height = expectedLabelSize.height;
    titleLabel.frame = newFrame;
    [self.view addSubview:titleLabel];

    }


}