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

展开式UITableViewCell无法读取struct元素问题排查

解决展开式单元格显示错误的问题

嗨,我看了你的代码,问题其实很典型,是新手写展开列表时容易踩的小坑!

问题核心

你在cellForRowAt方法的else分支里,错误地把展开后单元格的文本设置成了section的标题,而不是你存在sectionData里的cell1、cell2内容。另外还要注意:当section展开后,row=0是表头,row=1、2、3对应的是sectionData数组里的第0、1、2个元素,所以索引要减1,不然会触发数组越界错误哦。

修正后的代码

把cellForRowAt方法里的else分支改成这样:

else {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseidentifier, for: indexPath)
    // 用indexPath.row - 1对应sectionData的正确索引
    cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1]
    return cell
}

额外的小优化(可选)

你当前的代码里重复创建了cell变量,可以简化成更简洁的写法,避免冗余:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseidentifier, for: indexPath)
    if indexPath.row == 0 {
        cell.textLabel?.text = tableViewData[indexPath.section].title
    } else {
        cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1]
    }
    return cell
}

如果之后你想把Contact结构体的数据用到展开单元格里,还可以修改cellData的sectionData类型,比如:

struct cellData {
    var opened = Bool()
    var title = String()
    var sectionData = [Contact]() // 修改为Contact数组类型
}

// 在viewDidLoad初始化时调整数据源:
tableViewData = [cellData(opened: false, title: "title1", sectionData: [Contact(fullname: "张三", hello: "你好"), Contact(fullname: "李四", hello: "哈喽")]),
                // 其他section同理...]

// 然后在cellForRowAt里读取Contact的字段:
cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1].fullname

这样修改后,点击表头展开就能看到正确的内容啦,是不是很简单😉

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:08:37