首页 > 解决方案 > 无法从具有 indexPath 的单元格执行 segue

问题描述

我正在尝试执行 segue 并将数据从我的单元格中传递给 detailViewController。我已经尝试过使用虚拟数据,我可以将它们传递给 detailScreen,但是我想传递与单元格相关的数据。当我点击一个单元格时,我收到此错误“无法将 ViewController 类型的值转换为 MovieCell”,其中一行是 let selectedItem = ...感谢您的时间和精力这是我的代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   
        if segue.identifier == "detailSegue"
            {
            let destination = segue.destination as! DetailViewController
            let selectedItem = collectionView.indexPath(for: sender as! MovieCell)!
            let character = characters[selectedItem.item]
            destination.detailName = character.name
            destination.detailGender = character.gender
            destination.detailSpecies = character.species
            destination.detailStatus = character.status
            }
    
    }



override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {              
    performSegue(withIdentifier: "detailSegue", sender: self)
   }
    

标签: iosswift

解决方案


尝试使用:

    collectionView.indexPathsForSelectedItems.first

反而

    collectionView.indexPath(for: sender as! MovieCell)!

另外,我想为您推荐我的图书馆以应对这种情况:链接


推荐阅读