【发布时间】:2017-03-09 00:50:15
【问题描述】:
我正在学习制作 Instagram 风格应用程序的教程,该教程介绍了如何在一个集合视图中显示所有数据(图像、作者、喜欢等)。我试图做一些不同的事情,所以只有图像显示在集合视图中,然后如果点击图像,用户将被带到另一个视图控制器,其中显示图像和所有其他数据。
所以在我的带有集合视图 (FeedViewController) 的视图控制器中,我在类外部声明了我的帖子数组(Post 是包含所有上述数据的对象):
var posts = [Post]()
然后在FeedViewController 类中,我的cellForItemAt indexPath 看起来像这样:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
// creating the cell
cell.postImage.downloadImage(from: posts[indexPath.row].pathToImage)
photoDetailController.authorNameLabel.text = posts[indexPath.row].author
photoDetailController.likeLabel.text = "\(posts[indexPath.row].likes!) Likes"
photoDetailController.photoDetailImageView.downloadImage(from: posts[indexPath.row].pathToImage)
return cell
}
然后我显然也有一个函数来获取我可以在必要时发布的数据,但我认为问题是因为PhotoDetailController 不知道 indexPath(尽管我可能错了)。
当我运行应用程序并尝试查看FeedViewController 时,我遇到了崩溃fatal error: unexpectedly found nil while unwrapping an Optional value,突出显示photoDetailController.authorNameLabel 行。
我是否正确假设问题是因为 indexPath 仅在 FeedViewController 内的集合视图数据源中可用?如果是这样,我如何将该 indexPath 传递给 PhotoDetailController 以便我的代码正常工作?
感谢您的建议!
编辑:编辑了我的didSelectItem 方法:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let photoDetailController = self.storyboard?.instantiateViewController(withIdentifier: "photoDetail") as! PhotoDetailController
photoDetailController.selectedPost = posts[indexPath.row]
self.navigationController?.pushViewController(photoDetailController, animated: true)
}
和cellForItemAt:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
cell.postImage.downloadImage(from: posts[indexPath.row].pathToImage)
return cell
}
在PhotoDetailController:
var selectedPost: Post! 在类里面,那么:
override func viewDidLoad() {
super.viewDidLoad()
self.authorNameLabel.text = selectedPost[indexPath.row].author
self.likeLabel.text = "\(selectedPost[indexPath.row].likes!) Likes"
self.photoDetailImageView.downloadImage(from: selectedPost[indexPath.row].pathToImage)
}
但仍然出现错误use of unresolved identifier "indexPath
编辑 2:故事板
【问题讨论】:
-
使用集合视图的 didSelectItemAtIndexPath 并像我们对表格视图一样执行 segue。
标签: ios swift uicollectionview