我有一个基于 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.
}
}
更新:我修改了代码,现在收到错误
应用程序在运行时崩溃,我正在尝试解决:
最佳答案
发生崩溃是因为调用 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/