首页 > 解决方案 > 如何根据点击的单元格更改视图控制器的数据

问题描述

我正在做一个作业,在 ViewController A 中,我有三个单元格,钙、碱度、镁。我需要根据在 ViewController A 中点击的单元格更新 ViewController B。即,如果点击了碱度,则 ViewController B 上的标签应该说“碱度”,如果点击了钙,则 ViewController 2 应该说钙等。

我应该为每个单元格创建一个转场吗?或者我可以通过代码做到这一点吗?

我尝试使用 segue,但我觉得它对很多 segues 来说都是如此……我正在考虑使用单元标签?

还没有错误

标签: iosswiftuitableview

解决方案


没有segues的选项:

1) 在 interfaz builder 中ViewControllerB

2)ViewControllerA 需要符合UITableViewDelegate协议(或者UICollectionViewDelegate如果你使用UICollectionView

3)实现tableView(_:didSelectRowAt:)方法ViewControllerA

4)在方法中,实例化一个ViewControllerB实例,例子:

let vc = UIStoryboard(name: "nameofthestoryboard").instantiateViewController(withIdentifier: "ViewControllerB") as! ViewControllerB

5)获取使用索引路径选择的单元格。

let cell = tableview.cellForRow(at: indexPath) as! YourCellType

6) 为viewControllerB设置必要的信息,例如:

vc.chemicalElement = cell.chemicalElement

7) 显示您创建的 ViewControllerB 实例。

present(vc, animated: true, completion: nil) 

仅此而已。


推荐阅读