【问题标题】:How to display a set number of rows in small Table View with self-sizing cells如何在具有自调整大小的单元格的小型表格视图中显示一组行数
【发布时间】:2019-03-04 10:27:31
【问题描述】:

我有一个自定义表格视图类,它被配置为将表格视图高度设置为仅显示 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,则表格视图的大小不会正确调整。有解决办法吗?

【问题讨论】:

  • 由于单元格是自定尺寸的,您如何知道所有单元格的高度相同?当滚动可以找到大小不同的单元格时,如何确定一次显示任意 3 个单元格所需的高度?
  • 嗯,这是我的问题 :( 我希望将固有大小设置为前 3 个单元格的高度。有没有解决方案?如果没有,我必须将 rowHeight 设置为固定值: (

标签: swift uikit tableview


【解决方案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
    }
}

【讨论】:

  • 我已经尝试过了,虽然它可以正常获取单元格和东西,但它从具有动态尺寸的表格视图单元格中获得 0 高度。无论如何,感谢您的帮助,我将使用静态高度来实现这一目标
  • 我想你可以看看用systemLayoutSizeFitting(CGSize(width: providedWidth, height: 0)).height替换对intrinsicContentSize.height的检查
  • 好吧,在我的情况下,使用固定宽度而不是自动调整大小要简单得多。无论如何感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2019-04-23
相关资源
最近更新 更多