iOS8 实现具有动态高度的 heightForRowAtIndexPath

标签 ios uitableview swift

长话短说,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,我让它工作并符合我通过自动布局设置的约束,但无法在此处获取。

最佳答案

  1. 您描述的跳动滚动不是错误 - 这是因为您的估计高度与实际高度不够接近。
  2. 不要在 heightForRowAtIndexPath 方法中使单元格出队。基本上,您正在出列一个永远不会显示的单元格,因为您将它用于高度计算。

您有几个选择:

  • 改进您的估计高度预测。
  • heightForRowAtIndexPath 中,您可以使用自动布局来计算您的实际 高度,方法是创建一个未从 TableView 中出列的单元格实例。您可以通过以下方式做到这一点:
    • 以编程方式创建您的单元格,
    • .xib 中创建您的单元格,
    • 复制整个 View Controller 并以编程方式从中提取一个单元格
    • 复制 Storyboard中的单元格,然后 extracting it via a property

关于iOS8 实现具有动态高度的 heightForRowAtIndexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28247270/

相关文章:

iphone - 如何更改表格单元格详细信息披露按钮的颜色

ios - 分块解析 XML 文件,无需等待 Swift 中的完整下载

ios - 更改 TableViewController.swift 类

ios - 在数据源中隐藏 tableviewcell 或过滤器更好吗? (性能问题)

swift - 有没有办法将任何通用数字转换为 double ?

swift - 合并的订阅(在 :options:) operator

swift - 如何在 Swift 中翻译/本地化变量

html - 在iPhone中,键盘弹出时光标会停留在原来的位置

ios - 使用 Alamofire 和 SwiftyJSON 处理 JSON 并在 Swift 中添加到 UITableView

iOS 未收到通过 API 发送的 Firebase 推送通知