Static tableview如何让最后一个可见行占据剩余可用空间
静态TableView最后一个可见Cell占满剩余空间实现方案
实现思路
- 先预处理得到当前所有非隐藏的可见行索引数组
- 在返回行高的代理方法中,判断当前行是否为最后一个可见行
- 非最后一个可见行直接返回自动高度,隐藏行返回0
- 最后一个可见行的高度 = TableView总高度 - 其余所有可见行总高度 - Section头尾高度(如果有)
完整代码
首先定义可见行索引的辅助计算属性:
// 5个静态Cell对应row范围0~4,可根据实际情况调整 private var visibleRowIndexes: [Int] { return (0..<5).filter { !hideRow(at: IndexPath(row: $0, section: 0)) } }
然后实现行高代理方法:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // 隐藏行直接返回0 if hideRow(at: indexPath) { return 0 } let visibleRows = visibleRowIndexes // 非最后一个可见行使用自动高度 guard indexPath.row == visibleRows.last else { return UITableView.automaticDimension } // 计算前面所有可见行的总高度 var previousVisibleTotalHeight: CGFloat = 0 for row in visibleRows.dropLast() { let rowPath = IndexPath(row: row, section: 0) previousVisibleTotalHeight += self.tableView(tableView, heightForRowAt: rowPath) } // 减去Section头尾高度,无则可删除 let sectionHeaderHeight = tableView.rectForHeader(inSection: 0).height let sectionFooterHeight = tableView.rectForFooter(inSection: 0).height // 计算最终高度,避免负数设置最小高度 let finalHeight = tableView.bounds.height - previousVisibleTotalHeight - sectionHeaderHeight - sectionFooterHeight return max(finalHeight, 44) }
注意事项
- 所有隐藏的Cell需要设置
clipsToBounds = true,避免隐藏后Cell内容溢出显示 - 当行的隐藏状态变化时,调用
tableView.reloadData()刷新即可自动重新计算高度 - 如果TableView有全局的contentInset,计算finalHeight时需要对应减去inset的top和bottom值
内容的提问来源于stack exchange,提问作者CuriousMan
相关产品推荐
相关产品推荐

