当我尝试使用UITableViewAutomaticDimension scrollToRow时,表视图“跳转”。修复也使它跳跃

时间:2017-11-14 08:56:18

标签: ios uitableviewautomaticdimension

我遇到与this one相同的问题。 我试图实现一个建议的fix,而不是一个表格视图一直向上然后再次到最后一行,我得到了小跳跃。我需要让动画更流畅。是否可以使用UITableViewAutomaticDimension完成?

Here is a GIF showing the broken animation

我的代码如下:

@objc fileprivate func addNext() {
  guard rowsCount.value < cellModels.count else { return }

  let lastIndexPath = IndexPath(row: rowsCount.value, section: 0)
  rowsCount.value += 1

  CATransaction.begin()
  CATransaction.setCompletionBlock({ () -> Void in
    self.scrollToLastMessage()
  })

  tableView.update {
    tableView.insertRows(at: [lastIndexPath], with: .none)
  }
  CATransaction.commit()
}

func scrollToLastMessage()
{
  let bottomRow = tableView.numberOfRows(inSection: 0) - 1
  let bottomMessageIndex = IndexPath(row: bottomRow, section: 0)

  guard bottomRow >= 0
    else { return }

  CATransaction.begin()
  CATransaction.setCompletionBlock({ () -> Void in

    self.tableView.scrollToRow(at: bottomMessageIndex, at: .bottom, animated: true)
  })

  let contentOffset = tableView.contentOffset.y
  let newContentOffset = CGPoint(x:0, y:contentOffset + 1)  
  tableView.setContentOffset(newContentOffset, animated: false)

  CATransaction.commit()
}


extension UITableView {
  typealias Updates = () -> Void

  func update(_ updates: Updates) {
    beginUpdates()
    updates()
    endUpdates()
  }
}

提前致谢。

1 个答案:

答案 0 :(得分:2)

当我为表格视图添加估计的行高时,我解决了这个问题:

var cellHeightsDictionary: [Int:CGFloat] = [:]

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  cellHeightsDictionary[indexPath.row] = cell.frame.size.height
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  return cellHeightsDictionary[indexPath.row] ?? 44.0
}
相关问题