如何在SecondVC中正确展示对应tableViewCell的详细文本内容
修复方案
问题1:控制器间传值逻辑错误
你在点击跳转时给ListViewController传递了全量的result!.data数组,若你需要跳转后仅展示当前点击行的内容,仅需传递当前点击的条目即可;若需要跳转后展示全部3条内容对应显示,可跳过该步骤,直接修改后面的列表代码。
修改后的跳转代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let category = result?.data[indexPath.section] else { return } // 仅传递当前点击的条目,跳转后只展示对应内容 let vc = ListViewController(items: [category]) vc.title = category.title navigationController?.pushViewController(vc, animated: true) }
问题2:表头方法参数使用错误
你当前的表头取值用了固定的row变量,没有使用方法传入的section参数,导致所有表头永远取同一个下标的内容,修改如下:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return items[section]?.title }
问题3:单元格取值下标错误
UITableView的indexPath.row是每个section内的行号,每个section的row都是从0开始计数。如果你是1个section对应1条内容,每个section下只有1行,那么所有行的indexPath.row都是0,取items[indexPath.row]就会永远取第一条内容。修改如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell" , for: indexPath) // 用section作为下标取对应条目 cell.textLabel?.text = items[indexPath.section]?.content cell.textLabel?.font = UIFont.italicSystemFont(ofSize: 12.0) cell.textLabel?.textColor = .black cell.textLabel?.alpha = 0.5 return cell }
如果你的SecondVC是单section、3行结构,直接把numberOfRowsInSection返回items.count,cellForRowAt用indexPath.row取值即可,不需要改这部分。
内容的提问来源于stack exchange,提问作者Allahverdi
相关产品推荐
相关产品推荐

