2017-07-19 105 views
1

我有一个UICollectionView由图像数组填充。我想让用户点击图片并在新的UIViewController中进行预览。UICollectionView didSelectIotemAt问题

由于某种原因,didSelectItemAt方法未按预期工作。它不会抛出错误,它会被调用,只是真的没有任何反应。不知道我在这里做错了什么。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    print("did select item at was called") 
    let dashboardStoryboard = UIStoryboard(name: STORYBOARD_DASHBOARD, bundle:nil) 
    let destinationVC = dashboardStoryboard.instantiateViewController(withIdentifier: "PreviewPostImageVC") as! PreviewPostImageVC 
    destinationVC.selectedImage = arrayOfSelectedImages[indexPath.row] 
    self.navigationController?.pushViewController(destinationVC, animated: true) 
} 
+0

self.navigationController'nil'? –

回答

2

我想艾伦的评论指出了这个问题。如果你确定你的方法被调用(打印语句出现在控制台中),那么最可能的问题是self.navigationController是零。如果您使用的是可选链接,那么这个调用将会失败,如果它为零,这可能会或可能不是您想要的。尝试像这样改变它:

guard let navController = self.navigationController else { 
    print("Navigation Controller is nil!") 
    return 
} 
navController.pushViewController(destinationVC, animated: true) 
+0

你说得对。它是零。 'PreviewPostImageVC'没有嵌入到'UINavigationController'中。它是否需要嵌入? – Dani

+1

为了按照您尝试执行的方式按下导航控制器,集合视图需要位于导航控制器中。或者,您可以简单地使用'self.present(_:animated:completion:)'来代替模态表示。 –

+1

艾伦回答。是的,它必须嵌入在导航控制器中才能进行推送。如果你不使用导航控制器,那么使用模态演示是一个不错的选择。 –