长话短说,iOS8 在 UITableViewAutomaticDimension
上有一个错误
因此,您不能只调用 tableView.rowHeight = UITableViewAutomaticDimension
,然后调用 estimatedRowHeight,因为在某种程度上重新加载数据时,您最终会变得非常跳跃、看起来很奇怪的滚动。
缓解这种情况的方法显然是在 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
由于您无法在 heightForRowAtIndexPath:
中调用 cellForRowatIndexPath:
,我基本上将我的 cellForRowAtIndexPath
复制到另一个方法中并将其更改为高度。我似乎无法让它工作,因为我的 UILabel(单元格中具有动态高度的那个)符合一行,只是截断而不是继续 x 行,直到显示所有内容。
请注意,postBody
是具有动态高度的文本。
我的 cellForRowAtIndexPath:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = self.feed.dequeueReusableCellWithIdentifier("post") as UITableViewCell
var userName = cell.viewWithTag(1)! as UILabel
var timestamp = cell.viewWithTag(2)! as UILabel
var postBody = cell.viewWithTag(5)! as UILabel
var post = self.posts[indexPath.row]
userName.text = post.name
timestamp.text = post.timestamp
postBody.text = post.body
return cell
}
我的 heightForRowAtIndexPath:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var cell: UITableViewCell = self.feed.dequeueReusableCellWithIdentifier("post") as UITableViewCell
var userName = cell.viewWithTag(1)! as UILabel
var timestamp = cell.viewWithTag(2)! as UILabel
var postBody = cell.viewWithTag(5)! as UILabel
var post = self.posts[indexPath.row]
userName.text = post.name
timestamp.text = post.timestamp
postBody.text = post.body
cell.setNeedsLayout()
cell.layoutIfNeeded()
return cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
}
为什么不起作用?使用 UITableViewAutomaticDimension,我让它工作并符合我通过自动布局设置的约束,但无法在此处获取。
最佳答案
- 您描述的跳动滚动不是错误 - 这是因为您的估计高度与实际高度不够接近。
- 不要在
heightForRowAtIndexPath
方法中使单元格出队。基本上,您正在出列一个永远不会显示的单元格,因为您将它用于高度计算。
您有几个选择:
- 改进您的估计高度预测。
- 在
heightForRowAtIndexPath
中,您可以使用自动布局来计算您的实际 高度,方法是创建一个未从 TableView 中出列的单元格实例。您可以通过以下方式做到这一点:- 以编程方式创建您的单元格,
- 在
.xib
中创建您的单元格, - 复制整个 View Controller 并以编程方式从中提取一个单元格
- 复制 Storyboard中的单元格,然后 extracting it via a property
关于iOS8 实现具有动态高度的 heightForRowAtIndexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28247270/