iOS 动态创建 UILabels
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6634612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS create UILabels dynamically
提问by Peter Warbo
Sometimes I want my view to contain 5 UILabel
s, sometimes 3 and sometimes n.
有时我希望我的视图包含 5 UILabel
s,有时是 3 ,有时是n。
The number of UILabels depends on data that's fetched from a website.
UILabel 的数量取决于从网站获取的数据。
回答by tassinari
You'll have to make them in code instead of interface builder
你必须用代码而不是界面构建器来制作它们
for (int i = 0; i < n; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(/* where you want it*/)];
label.text = @"text"; //etc...
[self.view addSubview:label];
[label release];
}
回答by daveoncode
A generic answer for a generic question:
通用问题的通用答案:
while (labelsToDisplay)
{
UILabel *label = [[UILabel alloc] initWithFrame:aFrame];
[label setText:@"someText"];
[aViewContainer addSubview:label];
[label release];
}
回答by Enam
NSArray *dataArray;
float xCoordinate=10.0,yCoordinate=10.0,width=100,height=40;
float ver_space=20.0;
for (int i = 0; i <dataArray.count; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(xCoordinate,yCoordinate,width,height)];
label.text = [dataArray objectAtIndex:i];
[self.view addSubview:label];
yCoordinate=yCoordinate+height+ver_space;
}
回答by Priyam
UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(125, 12,170,20)];
lbl.text=@"IOS";
lbl.textAlignment = NSTextAlignmentCenter;
lbl.textColor = [UIColor whiteColor];
lbl.font = [UIFont fontWithName:@"AlNile" size:10.0];
lbl.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
lbl.layer.borderColor=[UIColor blackColor].CGColor;
lbl.layer.borderWidth=1.0f;
lbl.layer.cornerRadius = 6.0f;
[self.view addSubview:lbl];
回答by Mak
UILabel *lblTitle=[[UILabel alloc]init];
[lblTitle setFrame:CGRectMake(0, 0, 100, 100)];
[lblTitle setText:@"MAK"];
[lblTitle setBackgroundColor:[UIColor blueColor]];
[self.view addSubview:lblTitle];
-Here UILable will be created dynamically. -but property will be set differently.
- 这里将动态创建 UILable。- 但属性将设置不同。
回答by rafa
Create a TextView
to show the text on the labels and a NSArray
to contain the data.
创建 aTextView
以显示标签上的文本,创建 a以NSArray
包含数据。
For more information:
想要查询更多的信息: