[英]Dynamically create accessible UILabels in 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;
}
}
为每个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];
- (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];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.