gpt4 book ai didi

ios - 通过 IndexPath 从 CollectionViewCell 转到另一个 View Controller

转载 作者:行者123 更新时间:2023-11-28 10:18:08 24 4
gpt4 key购买 nike

我正在尝试将在 UICollectionView 中点击的单元格的 indexPath 传递给另一个 View Controller 。我似乎无法获取所选内容的 indexPath 并将其转到下一个 View Controller

我收到此错误:“无法将 Post 类型的值转换为 PostCell”

View Controller #1:

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let post = posts[indexPath.row]
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PostCell", forIndexPath: indexPath) as? PostCell {
cell.configureCell(post)
}
return cell
}
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let selectedPost: Post!
selectedPost = posts[indexPath.row]
performSegueWithIdentifier("PostDetailVC", sender: selectedPost)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PostDetailVC" {

//Error here: Could not cast value of Post to PostCell
if let selectedIndex = self.collection.indexPathForCell(sender as! PostCell){
print(selectedIndex)
}

if let detailsVC = segue.destinationViewController as? PostDetailVC {
if let selectedPost = sender as? Post {
print(selectedIndex)
detailsVC.post = selectedPost
detailsVC.myId = self.myId!
detailsVC.indexNum = selectedIndex
}

}

}
}

View Controller #2:

var indexNum: NSIndexPath!

override func viewDidLoad() {
super.viewDidLoad()

print(indexNum)
}

最佳答案

您传递的 Post 实例与预期的 PostCell 实例不匹配。

我建议通过索引路径

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("PostDetailVC", sender: indexPath)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PostDetailVC" {
guard let selectedIndexPath = sender as? NSIndexPath,
detailsVC = segue.destinationViewController as? PostDetailVC else { return }
print(selectedIndexPath)

let selectedPost = posts[selectedIndexPath.row]
detailsVC.post = selectedPost
detailsVC.myId = self.myId!
detailsVC.indexNum = selectedIndexPath
}
}

关于ios - 通过 IndexPath 从 CollectionViewCell 转到另一个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com