我已经看过几个帖子,但无法弄清楚问题
我想将数据从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()
}
}
但是当我运行这个时,我无法传递值并收到以下错误:
致命错误:在解包可选值时意外发现nil
请建议如何纠正此问题,谢谢
答案 0 :(得分:1)
我会建议你采用以下方法。在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分配给laber,如下所示。
self.Label.text = itemName
答案 1 :(得分:0)
不使用UIlabel label1,而是声明字符串变量eg。标题。并在代码中更改以下行。
类SelctionViewController:UIViewController {
var title = ""
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Label.text = title
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
prepareForSegue方法:而不是detailVC.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
}
}
}
答案 2 :(得分:0)
@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)
}
此代码现在工作得很好..查看