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

标签 ios swift firebase uicollectionview

我有一个基于 Firebase 数据填充的 UICollectionView。我创建了填充 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:

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

轮询 Controller :

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

}

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

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

enter image description here

最佳答案

发生崩溃是因为调用 prepare(for segue) 时 socket passLabel 尚未连接。

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

class PollController: UIViewController {

    @IBOutlet weak var passLabel: UILabel!

    var pass = ""

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

...

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

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

注意:不建议从 View (单元格)收集信息。获取索引路径并从模型(数据源数组)中读取信息。

关于ios - EXC_BAD_INSTRUCTION 将 UICollectionView 单元格数据传递给不同的 ViewController 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087926/

相关文章:

android - FirebaseRecyclerAdapter 检查查询是否成功完成

ios - “type of expression is ambiguous without more context” 使用结构属性作为字典键

ios - AsWebAuthenticationsession 是否支持通用链接?

ios - Swift 参数中的默认关键字

ios - 可以将 Analytics 划分为 DEBUG 和 RELEASE 吗?

ios - 仅在 Testflight 上崩溃

ios - iOS 蓝牙 LE 必须在 readRSSI 之前先进行读取或写入才能获取最新的 RSSI 值吗?

ios - 在后台/屏幕外加载 WKWebView

ios - 来自不透明的地址簿(_ :) in Swift 3

swift - 未声明的 Firebase 引用