我看过几个帖子,但无法弄清楚这个问题
我想将数据从UicollectionView Controller传递给我的UiviewController,这是详细信息
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Selection2" {
if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell) {
let detailVC = segue.destination as! SelectionViewController
//
let item = items1[indexPath.row]
//passing the item name which is selected
detailVC.label1.text = item.name1
}
}
}
这是SelectionViewController代码:
import UIKit
class SelctionViewController: UIViewController {
var label1 : UILabel!
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Label.text = self.label1.text
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
但是当我运行时,我无法传递值并获得以下错误:
致命错误:未包装可选值
时出乎意料地发现了无效请建议如何纠正,谢谢
我会建议您采用以下方法。在didSelectItemat方法中写下以下代码。
let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "Selection2") as! SelectionViewController
let item = items1[indexPath.row]
//Create string property itemName and pass the value
detailVC.itemName = item.name1
self.navigationController?.pushViewController(detailVC, animated: true)
在selectionViewController中,将itemname cass itemname如下所示。
self.label.text = itemName
@lazycoder,感谢您帮助我
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "Selection2") as! SelctionViewController
detailVC.itemName = self.items1[indexPath.row].name1
self.navigationController?.pushViewController(detailVC, animated: true)
}
现在,此代码工作正常。Cheers
而不是使用uilabel label1,而是声明字符串变量。标题。并更改代码中的以下行。
class selctionViewController:uiviewController {
var title = ""
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Label.text = title
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
Preparforsegue方法:而不是详细信息vc.label1.text,使用detailvc.title
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Selection2" {
if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell) {
let detailVC = segue.destination as! SelectionViewController
let item = items1[indexPath.row]
detailVC.title = item.name1 // instead of detailVC.label1.text, use detailVC.title
}
}
}