我正在尝试从collectionViewController中选择另一个ViewController,并且还尝试获取索引并适当地传递数据,但是当我选择一个单元格时,detailVC仅显示但没有打印出任何东西或任何东西
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == DETAIL_VC {
print("ITEM SELECTED ")
let vc = segue.destination as! DetailVC
guard let selectedIndexPath = sender as? IndexPath else { return }
let flickerPhoto = ServiceProvider.instance.flickerPhotos[selectedIndexPath.item]
print("ITEM SELECTED ")
vc.titleLabel.text = flickerPhoto.title
}
}
什么都不会打印
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let flickerPhoto = ServiceProvider.instance.flickerPhotos[indexPath.item]
let destinationVC = storyboard?.instantiateViewController(withIdentifier: DETAIL_VC) as! DetailVC
destinationVC.titleLabel.text = flickerPhoto.title
}
我收到错误Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
答案 0 :(得分:1)
您需要将源vc的黄色图标(而非单元格)中名为DETAIL_VC
的segue连接到目标,并在didSelectItemAt
内使用它
self.performSegue(withIdentifier:DETAIL_VC,sender:indexPath)
当您访问在加载vc之前为零的插座时崩溃,您可以尝试将数据作为字符串发送并将其设置在目标vc的viewDidLoad
中
destinationVC.titleValue = flickerPhoto.title
class DetailVC:UIViewController {
var titleValue:String = ""
// set it to the label text in `viewDidLoad`
override func viewDidLoad() {
super.viewDidLoad()
self.titleLabel.text = titleValue
}
}