Swift开发:点击CollectionViewCell后如何访问结构体carModel填充TableView
问题修复步骤
1. 修正错误遍历逻辑
你写的for循环用法完全错误:cars是所有汽车品牌的数组,本身没有carModel属性,且for i in xxx遍历数组时i是数组元素值不是索引,这段代码直接删掉即可,不需要手动遍历赋值,靠UITableView的数据源方法就能实现需求。
2. 给跳转的目标控制器添加接收数据的属性
在你的TableViewController类中添加如下属性,用来接收选中品牌对应的车型数组,同时把TableView的数据源逻辑移到该控制器中:
class TableViewController: UIViewController { // 新增接收属性 var selectedCarModels: [String] = [] @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self } } extension TableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 行数等于选中品牌的车型数量,不要写死5 return selectedCarModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell // 传入对应位置的车型字符串 cell.configure(with: selectedCarModels[indexPath.row]) return cell } }
3. 修改TableViewCell的配置方法
把原来接收Cars结构体的方法改成直接接收车型字符串,适配显示需求:
class TableViewCell: UITableViewCell { @IBOutlet var lbl: UILabel! // 修改配置方法参数 func configure(with model: String){ lbl.text = model } // 其他原有代码保持不变 }
4. 修改主控制器的点击跳转逻辑
点击CollectionView单元格时,取出对应品牌的车型数组,传给跳转的目标控制器:
extension ViewController:UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = storyboard?.instantiateViewController(identifier: "TableViewController") as? TableViewController // 传入选中品牌对应的车型数组 vc?.selectedCarModels = cars[indexPath.row].carModel self.navigationController?.pushViewController(vc!, animated: true) } }
5. 清理冗余代码
把主控制器ViewController的扩展中遵守UITableViewDataSource的声明、以及对应的两个TableView数据源方法全部删掉,这部分逻辑已经移到了TableViewController中。
完成以上修改后就能实现点击对应品牌,下一页展示该品牌所有车型的需求。
内容的提问来源于stack exchange,提问作者Nergezeev Alik
相关产品推荐
相关产品推荐

