我试图在ViewControllers之间传递数据而我没有使用故事板,所以我不能使用prepareForSegue
方法,这就是我所做的:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var vc = productDetailViewController()
self.navigationController?.pushViewController(productDetailViewController(), animated: true)
vc.product = self.shoes[indexPath.row]
}
答案 0 :(得分:1)
你在这里犯了两个错误:
1)尝试在vc中设置值,但发送一个新的视图控制器实例。
2)在按下控制器之后为控制器设置值。
所以,试试如下:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var vc = productDetailViewController()
vc.product = self.shoes[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
答案 1 :(得分:0)
交换最后两行......您的productDetailViewController
可能正在寻找初始化时的产品数据,这已经在推送时已经发生过。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// instantiate the new VC
var vc = productDetailViewController()
// set the data in the new VC first
vc.product = self.shoes[indexPath.row]
// then "show" the new VC --- NOT a new instance of productDetailViewController()
//self.navigationController?.pushViewController(productDetailViewController(), animated: true)</s>
self.navigationController?.pushViewController(vc, animated: true)
}