动态添加标签

时间:2011-04-07 07:01:04

标签: iphone uilabel

我需要一些指导。我正在解析XML并从中获取成员名称。名称应显示在标签上。现在我很困惑,因为任意数量的成员名称。如何根据会员姓名的数量添加标签。

示例:如果我得到5个名字,则应显示5个带名称的标签。

任何良好的编程指导?

我有一个scrollview,并且已经添加了一个UIVew作为子视图来显示一些静态标签。现在名称的标签应该显示在UIView上。

谢谢..

4 个答案:

答案 0 :(得分:2)

以下代码可用作获取标签数量的参考,具体取决于数组值。

为每个UILabel设置正确的帧...

 for(int i = 0 ; i  < [myArrayOfValue count]; i++)
    {
        UILabel* myLabel = [[UILabel alloc]initWithFrame:CGRectMake(myX,(myY + i*myHeight),myWidth,myHeight);
        myLabel.text = [myArrayOfValue objectAtIndex:i];

        ...........
        ............
        [myView addSubview:myLabel];
         myLabel.tag = i ;
        [myLabel release];
    }

答案 1 :(得分:2)

for (NSInteger i = 0, y = 50; i < [memberNameArray count]; i++, y += 30) {
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, y, 100, 25)];
    nameLabel.text = [memberNameArray objectAtIndex:i];
    [myScollView addSubview:nameLabel];
    [nameLabel release];
}

假设memberNameArray是NSString的数组,其中包含要显示的名称。此外,您还需要根据滚动视图中标签的位置更改框架的x, y, width, height值和y += 30

答案 2 :(得分:2)

UILabel *lblname=[[UILabel alloc]initWithFrame:CGRectMake(x,y,height,width)];
[lblname setText:@"any text"];
[lblname setBackgroundColor:[UIColor clearColor]];
[lblname setFont:[UIFont systemFontOfSize:15]];
[lblname setNumberOfLines:2];
[lblname setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:lblname];

答案 3 :(得分:0)

for(int i = 0; i&lt; [myArrayOfValue count]; i ++)     {         UILabel * myLabel = [[UILabel alloc] initWithFrame:CGRectMake(myX,(myY + i * myHeight),myWidth,myHeight);         myLabel.text = [myArrayOfValue objectAtIndex:i];

    ...........
    ............
    [myView addSubview:myLabel];
     myLabel.tag = i ;
    [myLabel release];
}
相关问题