Ios 如何获取UITableVIew中前n个单元格的高度?

Ios 如何获取UITableVIew中前n个单元格的高度?,ios,swift,uitableview,Ios,Swift,Uitableview,假设我想限制表视图的高度约束,使其仅显示特定数量的顶部单元格,那么如何获得它们的总高度 Swift 5: extension UITableView { func height(of top: Int, in section: Int = 0) -> CGFloat { let count = min(top, numberOfRows(inSection: section)) let height = (0..<count) .map { In

假设我想限制表视图的高度约束,使其仅显示特定数量的顶部单元格,那么如何获得它们的总高度

Swift 5:

extension UITableView {

func height(of top: Int, in section: Int = 0) -> CGFloat {

    let count = min(top, numberOfRows(inSection: section))

    let height = (0..<count)
        .map { IndexPath(row: $0, section: section) }
        .map { self.rectForRow(at: $0).height }
        .reduce(0, +)

    return height
}
}

加载数据后更新约束。

添加您迄今为止尝试过的内容。从我的答案中添加一个扩展-效果非常好。
extension UITableView {

func reloadData(completion: @escaping () -> ()) {
    CATransaction.begin()
    CATransaction.setCompletionBlock(completion)
    reloadData()
    CATransaction.commit()
}
}