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

如何通过代码设置UITableView不同行高?遇行高一致、单元格颜色异常

UITableView行高异常与单元格复用问题修复方案

一、解决单元格复用导致颜色统一为蓝色的问题

你的cellForRowAt方法存在两个问题:复用标识符生成逻辑错误,且未处理复用单元格的状态残留:

  1. 修正复用标识符:String(format: "cell", indexPath.row)没有占位符,无论行号多少都会生成"cell",且无需为每行单独设置标识符,统一使用一个即可:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 使用统一的复用标识符
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ShopTableViewCell
    
    // 先重置背景色,避免复用残留之前的样式
    cell.viewInCollection.backgroundColor = .white
    
    // 根据行号设置对应颜色
    if indexPath.row == 0 {
        cell.viewInCollection.backgroundColor = .blue
    } else if indexPath.row == 1 {
        cell.viewInCollection.backgroundColor = .gray
    } else {
        cell.viewInCollection.backgroundColor = .red
    }

    return cell
}
  1. 确保单元格注册正确:
    • 代码注册:在viewDidLoad中添加tableView.register(ShopTableViewCell.self, forCellReuseIdentifier: "cell")
    • Storyboard/XIB:确保原型单元格的复用标识符设置为"cell"

二、解决行高不生效的问题

行高全部显示为50,核心原因是UITableView代理未正确绑定,或单元格布局初始化逻辑不完整:

  1. 绑定TableView代理:
    • 代码方式:在viewDidLoad中添加tableView.delegate = self
    • Storyboard方式:将tableView的delegate拖拽关联到当前ViewController
  2. 重构单元格布局代码:原ShopTableViewCell仅在awakeFromNib中初始化布局,但代码创建的单元格不会触发该方法,导致视图未正确添加。修改为通用初始化逻辑:
class ShopTableViewCell: UITableViewCell {
    
    let viewInCollection = UIView()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupLayout()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLayout()
    }
    
    private func setupLayout() {
        contentView.addSubview(viewInCollection)
        viewInCollection.translatesAutoresizingMaskIntoConstraints = false
        
        let margins = contentView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            viewInCollection.topAnchor.constraint(equalTo: margins.topAnchor),
            viewInCollection.bottomAnchor.constraint(equalTo: margins.bottomAnchor),
            viewInCollection.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
            viewInCollection.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
        ])
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}
  1. 清除行高覆盖配置:
    • 代码中不要设置tableView.rowHeight = 50这类固定值
    • Storyboard中,将tableView的Row Height设为Automatic,不要勾选Automatic Dimension(手动指定行高时)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:14:53