将 UICollectionView 单元格数据传递给不同的 ViewController 时的 EXC_BAD_INSTRUCTION [英] EXC_BAD_INSTRUCTION When Passing UICollectionView Cell Data to Different ViewController

查看:13
本文介绍了将 UICollectionView 单元格数据传递给不同的 ViewController 时的 EXC_BAD_INSTRUCTION的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于 Firebase 数据填充的 UICollectionView.我创建了填充 UICollectionView 的自定义单元格:

I have a UICollectionView that I am populating based on Firebase data. I have created custom cells that populate the 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 中单击单元格的 pollQuestion 变量并将其传递给另一个 ViewController:

I am attempting to access the pollQuestion variable of the clicked cell in the UICollectionView and pass it to another 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
        }
    }
}

投票控制器:

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.
  }

}

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

UPDATE: I have revised the code and am now receiving the error

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

The app is crashing at runtime, and I am trying to resolve:

推荐答案

调用prepare(for segue时,出口passLabel还未连接导致崩溃.

The crash occurs because the outlet passLabel is not connected yet when prepare(for segue is called.

您必须在 PollController 中声明一个(临时)变量并在 viewDidLoad

You have to declare a (temporary) variable in PollController and set the label in viewDidLoad

class PollController: UIViewController {

    @IBOutlet weak var passLabel: UILabel!

    var pass = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        passLabel.text = pass
    }

...

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

In prepare(for segue set the variable rather than the text property of the label:

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

注意:不建议从视图(单元格)收集信息.获取索引路径并从model(数据源数组)中读取信息.

Note: It's not recommended to gather information from the view (cell). Get the index path and read the information from the model (data source array).

这篇关于将 UICollectionView 单元格数据传递给不同的 ViewController 时的 EXC_BAD_INSTRUCTION的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆