iOSdynamic创buildUILabels

有时我希望我的视图包含5个UILabel ,有时是3,有时候是n

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

您必须使用代码而不是界面构build器来制作它们

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

通用问题的一般答案:

 while (labelsToDisplay) { UILabel *label = [[UILabel alloc] initWithFrame:aFrame]; [label setText:@"someText"]; [aViewContainer addSubview:label]; [label release]; } 
  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; } 
  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]; 
 UILabel *lblTitle=[[UILabel alloc]init]; [lblTitle setFrame:CGRectMake(0, 0, 100, 100)]; [lblTitle setText:@"MAK"]; [lblTitle setBackgroundColor:[UIColor blueColor]]; [self.view addSubview:lblTitle]; 

– 这里UILable将被dynamic创build。 – 但财产将被设置不同。