Динамически создавать доступные UILabels в objective-c

#iphone #objective-c

#iPhone #objective-c

Вопрос:

Я пытаюсь динамически создавать UILabels для каждой буквы в слове в objective-c. Как вы можете видеть, я передаю количество букв, которые будут использоваться для слова, и мне нужно заполнить раздел комментариев ниже:

 -(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;
    }
}
  

Комментарии:

1. Вы пытались создать экземпляр массива var из UILabels?

2. когда вы вызываете этот метод? сколько раз вызывается этот метод? Вызывается ли это один раз, а затем после того, как вы просто измените буквы?

3. @Jorge @Ravin смотрите выше правки для некоторого кода, который мне удалось написать. Проблема в том, как расположить эти элементы и центрировать их сейчас.

Ответ №1:

Задайте значение тега для каждой UILabels

например

 #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];
  

Ответ №2:

 - (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];

    }


}