2015-08-28 69 views
2

我有tableView,當我鍵入我想要自動高度單元格。但我不知道如何解決它。我的第一個想法是:添加文本後的自動高度單元格

self.chatTableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text = new_char 
self.chatTableView.cellForRowAtIndexPath(indexPath)?.sizeToFit() 
self.chatTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false) 

當我有.sizeToFit()我的結果這一行看起來是這樣的: first result 但是,當我評論這行:

self.chatTableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text = new_char 
self.chatTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false) 

我的結果看起來這樣的: econd result

有什麼方法可以解決它?

回答

1

您已直接更改了UITableViewCell的高度。但是單元格的高度在UITableView中處理。爲了使這項工作,你必須做兩件事情:

1.使用自定徑細胞:

這個代碼兩行只需添加到您的viewDidLoad方法:

override func viewDidLoad() { 
     super.viewDidLoad() 
     ... 
     tableView.rowHeight = UITableViewAutomaticDimension 
     tableView.estimatedRowHeight = 40 
    } 

estimatedRowHeight是隻用於計算滾動條的大小和位置,因此您只需將單元的正常預期高度放在此處即可。你改變了文本

2.重新加載電池後,你改變了你的電池的標籤的文字,你必須告訴UITableView重新裝入此單元格,以便其高度被調整。你通過調用這個方法來做到這一點:

func addSomeText() { 
    // add the text to your data source 

    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) 
} 

很明顯,indexPath是你的單元格的indexPath。

一件重要的事情:您不能直接將新文本添加到單元格。相反,您必須將其添加到您的dataSource。否則文本將在重新加載後消失,因爲該單元格在出列時從dataSource獲取文本。

+0

我可以直接添加文本到單元格:) – Wraith

+0

好的,那麼你添加的文本不同於我做的。甚至更好;-) – joern

相關問題