【问题标题】:How to present data on a view controller, based on the cell that was tapped in the previous controller如何根据在前一个控制器中点击的单元格在视图控制器上呈现数据
【发布时间】:2019-07-12 08:46:33
【问题描述】:

我有视图控制器 A,它有五个静态集合视图单元格,带有一个标题标签和一个描述标签。根据点击的单元格,我需要转到 View Controller B,View Controller B 将显示与该数据关联的产品列表。

我试图这样做是 didSelect 方法,但我认为我错了......我意识到在使用打印语句后我正确地让导航工作,我也可以在视图控制器 A 上打印名称标签,但是传递给视图控制器 B 的数据为零。

查看控制器 A

var 参数:[参数] = [ 参数(名称:“碱度”,描述:“这里的描述是关于稳定测量的重要性”), Parameter(name: "Calcium", description: "这里的描述是关于稳定测量的重要性"), // 减少数量,这样我就不会在这里占用太多空间 ]

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   let selectedCell = parameters[indexPath.row]
    // Create an instance of DeatailViewController and pass that variable
    let destinationVC = DetailViewController()
    destinationVC.dataReceived = selectedCell.name
    self.performSegue(withIdentifier: "segueID", sender: self)

}

视图控制器 B

只有一个打印语句。

预期:将我点击的单元格的名称传递给第二个 VC,(目前)但我想在名称标签中显示与每个元素关联的产品列表。例如:碱度会显示碱度产品(我应该在不同型号中定义这个)吗?

错误: 在 VCB 上显示 nil

建议:

也许在 didSelectRow 中使用索引路径?

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    使用segue传递数据时需要实现prepareForSegue

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
        self.performSegue(withIdentifier: "segueID", sender:parameters[indexPath.row]) 
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segueID" {
             let vc = segue.destination as! DetailViewController
             destinationVC.dataReceived = sender as! Model // Model is type of array parameters
        }
    }
    

    但是用vc实例化DetailViewController()你需要使用present/push

    let destinationVC = DetailViewController()
    destinationVC.dataReceived = selectedCell.name
    self.present(destinationVC,animated:true)
    

    第二种方式呈现DetailViewController() 会使应用程序崩溃,因为您没有从storyboard 加载vc,所以它应该是这样的

    let vc = self.storyboard!.instantiateViewController(withIdentifier: "DetailID") as! DetailViewController
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 segue,我会通过执行以下操作来实现:

       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
              if segue.identifier == "segueID" {
                  if let destinationVC = segue.destination as? DetailViewController {
                  destinationVC.dataReceived = selectedCell.name
                  }
              }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-11-20
        • 1970-01-01
        • 2020-02-13
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多