2016-12-01 62 views
0

我是iOS新手,我正面临着动态创建UILabel的问题。我需要根据webservice的数据改变它的高度和Y位置。 我的代码是这样的如何在Objective c中动态设置UILabel高度?

NSMutableArray *remarkarray =[[NSMutableArray alloc] init]; 
      remarkarray=[responsedict valueForKey:@"Key"]; 
      NSString *RemarkString=[NSString stringWithFormat:@"%@",[remarkarray objectAtIndex:0]]; 
      remarklbl.text=RemarkString; 
      remarklbl.numberOfLines=0; 
      [remarklbl sizeToFit]; 

我有这样

enter image description here

但其Y位置是固定创建的UILabel。我需要创建一个UILabel,其中我可以根据其中的文本更改高度和Y位置。就像在推进这一

enter image description here

谢谢!

+0

u能elobrate,我可以根据它的文字改变高度和Y位置搜索周围。 –

+0

您可以使用自动布局并在行之间创建约束,以确保标签之间有固定的间距,而不管标签可以增长到多少行。 –

+0

您想根据文本更改标签高度 –

回答

2

您可以在故事板声明两个标签,这样做很容易。

以下是步骤。

  1. 在您的viewController中拖拽两个UILabel,并选择第一个UILabel并设置下图所示的约束。

enter image description here

  • 选择第二个标签,并添加以下约束。
  • enter image description here

  • 选择这两个标签和设置numberOfLines为零。
  • 现在你可以从代码动态设置文本。

    Adding text from code... Output here..

    +0

    这个答案中的标签是如何动态的? – User511

    +0

    Bcoz我将numberOfLine设置为零,并没有将标签的高度设置为固定。因此,它会根据标签的内容自动设置。 –

    +0

    它会自动设置标签的高度而不是动态标签。 – User511

    0

    所有你需要做的是:

    float x=10.0,y=10.0,height=40; 
    float verticalSpace=20.0; 
    
    
    for (int i = 0; i < 10; i++) 
    { 
        UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(x, y,50,height)]; 
        label.text = @"dummy text";// It could be from array as well if you want to add different text for each label. Eg: label.text = [arr objectAtIndex:i]; 
        [self.view addSubview:label]; 
        y = y +height+ verticalSpace; 
    
    } 
    
    +0

    y的位置和高度变化的代码 –

    +0

    我已经更新了我的答案。 – User511

    0

    您可以用关键词“汽车动态布局标签高度”