Swift 如何识别UITableView各分区首尾行并隐藏cell内指定视图
问题根因
- Cell复用状态未重置:你仅在当前行是分区末行时设置了
bottomView隐藏,没有为非末行的Cell显式设置bottomView为显示状态。UITableView的Cell是复用的,滚动时之前被设置为隐藏的Cell会被用到其他位置,导致状态错乱。 - 缺少首行判断逻辑:当前代码仅实现了末行隐藏
bottomView的判断,还未补充首行隐藏topView的逻辑。 - 建议优先从数据源获取分区行数,而非调用
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
相关产品推荐
相关产品推荐

