我有 tableView,当我输入时我想要自动高度单元格。但我不知道如何解决它。我的第一个想法是:
self.chatTableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text = new_char
self.chatTableView.cellForRowAtIndexPath(indexPath)?.sizeToFit()
self.chatTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
当我在 .sizeToFit()
这行时,我的结果如下所示:
但是当我评论这一行时:
self.chatTableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text = new_char
self.chatTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
有什么办法可以解决吗?
最佳答案
您已经直接更改了 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
获取其文本。
关于swift - 添加文本后自动高度单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32271856/