如何在具有自定义单元格的小型表视图中显示一定数量的行

时间:2019-03-04 10:27:31

标签: swift uikit tableview

我有一个自定义表格视图类,该类配置为将表格视图高度设置为仅显示3行。这意味着如果有20行,表格视图的大小将显示前3行,并允许用户滚动。

仅当我设置了静态rowHeight

时,此代码才有效
class CannedRepliesTableView: UITableView {

    /// The max visible rows visible in the autocomplete table before the user has to scroll throught them
    let maxVisibleRows = 3

    open override var intrinsicContentSize: CGSize {

        let rows = numberOfRows(inSection: 0) < maxVisibleRows ? numberOfRows(inSection: 0) : maxVisibleRows
        return CGSize(width: super.intrinsicContentSize.width, height: (CGFloat(rows) * rowHeight))
    }
}

如果将UITableViewAutomaticDimension设置为rowHeight,则无法正确调整表视图的大小。有解决办法吗?

1 个答案:

答案 0 :(得分:1)

这将是改善您现有资产的一种方法。我没有访问intrinsicContentSize进行此计算的经验,也没有在本地进行测试(语法除外),但是如果以前可以工作,那么也应该如此。

基本上,您正在创建一个包含maxVisibleRows indexPaths 的数组。如果数量较少,则fetchedIndexesCount可以防止 indexOutOfBounds 崩溃。有了数组后,就可以迭代每个对应的单元格并获取其大小,最后对其求和。

class CannedRepliesTableView: UITableView {

    var focussedSection = 0
    let maxVisibleRows = 3

    open override var intrinsicContentSize: CGSize {
        return CGSize(width: super.intrinsicContentSize.width, height: calculateHeight())
    }

    private func calculateHeight() -> CGFloat {
        guard let indexPaths = startIndexes(firstCount: 3) else {
            // Your table view doesn't have any rows. Feel free to return a non optional and remove this check if confident there's always at least a row
            return 0
        }
        return indexPaths.compactMap({ cellForRow(at: $0)?.intrinsicContentSize.height }).reduce(0, +)
    }

    private func startIndexes(firstCount x: Int) -> [IndexPath]? {
        let rowsCount = numberOfRows(inSection: focussedSection)
        let fetchedIndexesCount = min(x, rowsCount)
        guard fetchedIndexesCount > 0 else {
            return nil
        }
        var result = [IndexPath]()
        for i in 0..<fetchedIndexesCount {
            result.append(IndexPath(row: i, section: focussedSection))
        }
        return result
    }
}