首页 > 解决方案 > 如何以编程方式将数据从表视图控制器传递到另一个控制器?

问题描述

我在将数据(特别是图像和两个标签)从表视图控制器传递到另一个控制器时遇到问题。我的目标是,当用户从表格视图中选择一个选项时,它将转到下一个控制器并显示他们选择的选项的特定图像和信息。有没有我只是缺少的简单修复?

标签: iosswiftuitableviewuikit

解决方案


在您的目标控制器上创建一个与您要传递的变量类型相同的变量,并使用 did select 方法导航到目标控制器并传递如下数据:

func tableView(_ tableView: UITableView, didSelectRowA indexPath: IndexPath) {
    let nextVC = DestinationVC()
    nextVC.info = yourArray[indexPath.row].info
    nextVC.modallyPresentingStyle = .fullscreen
    self.present( nextVC,  animated: true,  completion: nil)
}

传递你想要的所有数据,比如信息数据,不要忘记在目标控制器上创建具有相同声明类型的所有变量,例如,如果你想传递一个图像,那么在你的目标 VC 中创建一个图像变量,如下所示

 var selectedImage = UIImage()

然后将其添加到上一个方法中

nextVC.selectedImage = yourImage // if not part of a cell at index path
nextVC.selectedImage = yourArray[indexpath.row].yourImage // if it is related to specific cell at index path

推荐阅读