Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 866
Peter Warbo Avatar asked Jul 09 '11 12:07

Peter Warbo


3 Answers

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];
 }
like image 119
tassinari Avatar answered Nov 17 '22 19:11

tassinari


A generic answer for a generic question:

while (labelsToDisplay) 
{
    UILabel *label = [[UILabel alloc] initWithFrame:aFrame];
    [label setText:@"someText"];
    [aViewContainer addSubview:label];
    [label release];
}
like image 45
daveoncode Avatar answered Nov 17 '22 19:11

daveoncode


   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;
   }
like image 4
Enam Avatar answered Nov 17 '22 17:11

Enam