2016-03-01 90 views
0

我試圖從一個網站使用博客文章並在iPhone應用程序中顯示它們。標題和副標題可以是多行的。創建一個多行UILabel

我無法計算出如何根據內容更改標籤的高度。

我能夠實現這個使用UITextView,但這是正確使用這個對象?

謝謝! 〜M

+0

更多的細節可能會更好。你使用的是tableView嗎?如果是這樣,你使用的是自定義的tableViewCell Nib,還是僅僅使用默認的單元格? – ZGski

+0

不...沒有tableView ...雖然我確實看到很多人都在使用這種方法,但也許我應該重新考慮使用簡單的視圖。 謝謝! –

回答

2

當然,您可以根據文本動態更改UILabel的高度。只要確保該的UILabel具有numberOfLines = 0,並按照此示例中的答案:ios dynamic sizing labels

對於一個完整的答案,這裏是你可以用它做的代碼...

計算的高度,你的文本將會出現在您的標籤中,然後根據該尺寸設置標籤的框架:

//Calculate the expected size based on the font and linebreak mode of your label 
CGSize maximumLabelSize = CGSizeMake(296,9999); 

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
        constrainedToSize:maximumLabelSize 
        lineBreakMode:yourLabel.lineBreakMode]; 

//adjust the label the the new height. 
CGRect newFrame = yourLabel.frame; 
newFrame.size.height = expectedLabelSize.height; 
yourLabel.frame = newFrame;