展开式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
相关产品推荐
相关产品推荐

