You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 如何识别UITableView各分区首尾行并隐藏cell内指定视图

问题根因

  1. Cell复用状态未重置:你仅在当前行是分区末行时设置了bottomView隐藏,没有为非末行的Cell显式设置bottomView为显示状态。UITableView的Cell是复用的,滚动时之前被设置为隐藏的Cell会被用到其他位置,导致状态错乱。
  2. 缺少首行判断逻辑:当前代码仅实现了末行隐藏bottomView的判断,还未补充首行隐藏topView的逻辑。
  3. 建议优先从数据源获取分区行数,而非调用tableView.numberOfRows(inSection:),避免数据源和UITableView缓存不一致导致的计算错误。

修复后代码

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! cell
    let item = sections[indexPath.section].items[indexPath.row]
    // 直接从数据源获取当前分区的总行数,更稳定
    let totalRow = sections[indexPath.section].items.count
    
    // 处理topView显隐:首行隐藏,其余行显示
    cell.topView.isHidden = (indexPath.row == 0)
    // 处理bottomView显隐:末行隐藏,其余行显示
    cell.bottomView.isHidden = (indexPath.row == totalRow - 1)
    
    return cell
}

小提示:Swift类名建议使用大驼峰命名,你自定义的Cell类cell可以改成CustomTableViewCell之类的命名,更符合规范,也避免和系统类名混淆。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:15:06