Dynamically create accessible UILabels in objective-c
I'm trying to dynamically create UILabels for each letter in a word in objective-c. As you can see, I'm passing in the number of letters that will be used for the word and I need to fill in the commented section below:
-(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
}
}
The labels need to be accessible to change. If I want to change one letter from A -> B, then I would like to be able to do that dynamically. Any help would be appreciated here.
Right now here's what I have, however, I'd like to be able to center the group of labels in the middle of the screen:
-(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;
}
}
Set a tag value for each 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];
......
}
}
Then to accessed a label a position 10 for example
UILabel *label = (UILabel*)[self viewWithTag:LABEL_TAG+10];
- (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];
}
}
精彩评论