将UICollectionView单元格数据传递给不同的ViewController时EXC_BAD_INSTRUCTION

我有一个基于Firebase数据填充的UICollectionView。 我已经创build了填充UICollectionView的自定义单元格:

import UIKit import Material class PollCell: CollectionViewCell { var key: String? { get { return self.key } } @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var pollQuestion: UILabel! public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } 

我正在尝试访问UICollectionView中单击单元格的pollQuestionvariables,并将其传递给另一个ViewController:

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toPoll" { let pollViewController = segue.destination as! PollController if let cell = sender as? PollCell { pollViewController.passLabel.text = cell.pollQuestion.text } } } 

PollController:

 import UIKit class PollController: UIViewController { @IBOutlet weak var passLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } 

}

更新:我修改了代码,现在收到错误

该应用程序在运行时崩溃,我试图解决:

在这里输入图像说明

发生崩溃是因为出口passLabelprepare(for segue时尚未连接prepare(for segue被调用。

您必须在PollController声明一个(临时)variables,并在viewDidLoad设置标签

 class PollController: UIViewController { @IBOutlet weak var passLabel: UILabel! var pass = "" override func viewDidLoad() { super.viewDidLoad() passLabel.text = pass } ... 

prepare(for segue设置variables而不是标签的text属性:

 let pollViewController = segue.destination as! PollController if let cell = sender as? PollCell { pollViewController.pass = cell.pollQuestion.text } } 

注意:不build议从视图 (单元格)收集信息。 获取索引path并从模型 (数据源数组)中读取信息。

而不是调用cellForItem,它给你一个新的单元格,你应该使用传递给你的单元格作为发件人。

 if let cell = sender as? PollCell { pollViewController.passLabel.text = cell.pollQuestion.text }