Peter Warbo
Peter Warbo

Reputation: 11710

iOS create UILabels dynamically

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.

Upvotes: 15

Views: 26890

Answers (6)

Enam
Enam

Reputation: 69

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

Upvotes: 4

Mak
Mak

Reputation: 49

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.

Upvotes: 0

Priyam
Priyam

Reputation: 69

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

Upvotes: 0

daveoncode
daveoncode

Reputation: 19578

A generic answer for a generic question:

while (labelsToDisplay) 
{
    UILabel *label = [[UILabel alloc] initWithFrame:aFrame];
    [label setText:@"someText"];
    [aViewContainer addSubview:label];
    [label release];
}

Upvotes: 9

tassinari
tassinari

Reputation: 2363

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

Upvotes: 34

Related Questions