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

Swift开发UITableView高度自适应及最后Cell元素隐藏问题

问题解决方案

1. 实现tableView高度随cell数量自动变化

你当前给tableView设置了固定282的高度约束,修改方案如下:

  • 第一步:调整约束声明,把高度约束存为全局属性方便后续更新
// 声明高度约束属性
var tableViewHeightConstraint: Constraint?

makeTableView.snp.makeConstraints { make in
    make.top.equalTo(possibleLabel.snp.bottom).offset(10)
    make.leading.trailing.equalToSuperview()
    // 存储高度约束,初始值可随便设置,后续会动态更新
    self.tableViewHeightConstraint = make.height.equalTo(0).constraint
}
  • 第二步:每次products数组变更、调用makeTableView.reloadData()后,更新高度约束
// 每个cell高度固定为94,直接计算总高度
let totalTableHeight = CGFloat(products.count) * 94
tableViewHeightConstraint?.update(offset: totalTableHeight)
// 触发父视图布局刷新
view.layoutIfNeeded()

2. 仅隐藏最后一行cell的下划线

你的代码存在三个明显问题:

  • 判断逻辑错误:当前无论是不是最后一行,都把下划线设为了隐藏状态
  • 属性访问错误:if分支访问的是cell.makeView.underLine,else分支访问的是cell.make.underLine,两个属性不一致
  • 重复声明cell变量,逻辑冗余

修正后的代码如下:

private func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 提前做类型转换,避免重复声明
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MakeTableViewCell
    cell.selectionStyle = .none
    cell.backgroundColor = .clear
    
    // 先校验数据源非空,再判断是否为最后一行
    let isLastRow = !products.isEmpty && indexPath.row == products.count - 1
    // 仅最后一行隐藏下划线,其余行正常显示
    cell.makeView.underLine.isHidden = isLastRow
    
    return cell
}

额外校验点:请确认你numberOfRowsInSection代理方法的返回值为products.count,否则行号判断会不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:45:03