2016-09-24 75 views
0

在我的故事板中,我有一個UITableView動態生成UITableViewCell s。每個單元包含2個標籤和1個文本視圖:如何將UITableViewCell高度調整爲裏面的UITextView的內容?

enter image description here

我有調整文本框的大小,以文本的量的代碼:

let fixedWidth = cell.myComment.frame.size.width 
cell.myComment.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max)) 
let newSize = cell.myComment.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max)) 
var newFrame = cell.myComment.frame 
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height) 
cell.myComment.frame = newFrame; 

並能正常工作,當我設置我的TextView的背景色爲紅色我看到:

enter image description here

和電池本身 - 我設置SI澤在這裏:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{ 
    if indexPath.row == 0 { 
     return 100//this is my static cell 
    } 
    else { 
     return 117; //for now it's hardcoded - how can I set this value dynamically based on content? 
    } 
} 

因此,正如我在上面的評論中寫道 - 我怎麼可以設置單元格的高度動態的基於文本的文本視圖中的金額是多少?

回答

3

,這是讓自調整大小表格單元格(自動版式爲主,我建議)的主要內容如下:

  • 你的子視圖添加到的UITableViewCell
  • 提供限制你的子視圖之間的contentViewcontentView使您的子視圖覆蓋表格單元格的所有邊緣。在您的情況下,這可能意味着將UITextView的邊緣leading,trailing,topbottom對齊到contentView的對應邊緣。
  • 將行高設置爲UITableViewAutomaticDimension而不是硬編碼的CGFloat
  • 控制器中的某處用tableView.estimatedRowHeight = x(硬編碼常數很好,這是爲了提高性能)提供高度估計。
+0

嗯,所以通過這樣做,我仍然需要負責調整文本視圖的高度的代碼的一部分? – user3766930

+0

沒有。只要你限制邊緣,UITextView足夠聰明,可以將文本包裝到第二行。它像'UILabel'一樣,基於其文本具有內在的內容大小。 – Connor

+0

感謝人,作品像魅力:) – user3766930

相關問題