iOS动态创建UILabels

时间:2011-07-09 12:03:55

标签: ios dynamic uilabel

有时我希望我的观点包含5个UILabel s,有时3个,有时 n

UILabel的数量取决于从网站获取的数据。

6 个答案:

答案 0 :(得分:34)

您必须在代码而不是界面构建器

中创建它们
 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];
 }

答案 1 :(得分:9)

一般性问题的通用答案:

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

答案 2 :(得分:4)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

UILabel *lblTitle=[[UILabel alloc]init];
[lblTitle setFrame:CGRectMake(0, 0, 100, 100)];
[lblTitle setText:@"MAK"];
[lblTitle setBackgroundColor:[UIColor blueColor]];
[self.view addSubview:lblTitle];

-Here UILabel将动态创建。 - 但财产的设置方式不同。

答案 5 :(得分:-1)