2016-12-01 58 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

    您可以用關鍵詞「汽車動態佈局標籤高度」