小编典典

将UICollectionView单元格数据传递到其他ViewController时EXC_BAD_INSTRUCTION

swift

我有一个基于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
        }
    }
}

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

}

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

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

在此处输入图片说明


阅读 298

收藏
2020-07-07

共1个答案

小编典典

发生崩溃是因为在调用passLabel时尚未连接插座prepare(for segue

您必须在中声明(临时)变量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
    }
}

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

2020-07-07