iOS create UILabels dynamically

2020-02-26 05:31发布

Sometimes I want my view to contain 5 UILabels, sometimes 3 and sometimes n.

The number of UILabels depends on data that's fetched from a website.

6条回答
可以哭但决不认输i
2楼-- · 2020-02-26 06:03

A generic answer for a generic question:

while (labelsToDisplay) 
{
    UILabel *label = [[UILabel alloc] initWithFrame:aFrame];
    [label setText:@"someText"];
    [aViewContainer addSubview:label];
    [label release];
}
查看更多
在下西门庆
3楼-- · 2020-02-26 06:11

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];
 }
查看更多
趁早两清
4楼-- · 2020-02-26 06:12
   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;
   }
查看更多
够拽才男人
5楼-- · 2020-02-26 06:17
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.

查看更多
唯我独甜
7楼-- · 2020-02-26 06:22
 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];
查看更多
登录 后发表回答