【问题标题】:How to pass data between collection views Swift如何在集合视图之间传递数据 Swift
【发布时间】:2021-10-13 12:01:54
【问题描述】:

我想将一些数据从一个集合视图传递到另一个集合视图,但出现以下错误:

无法转换类型“[IndexPath]?”的值到预期的参数类型'Int'

当我按下一个单元格时,我想向另一个集合视图显示一些数据。

这是代码。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        performSegue(withIdentifier: "showItems", sender: self)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? ItemsViewController
        {


///Below is the error
            destination.items = guys[collectionView.indexPathsForSelectedItems]  

        }
    }

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    发生错误是因为guys 数组需要Int 索引,而不是可选的索引路径数组。

    一种解决方案是在sender 参数中发送indexPath

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        performSegue(withIdentifier: "showItems", sender: indexPath)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? ItemsViewController
        {
            let indexPath = sender as! IndexPath
            destination.items = guys[indexPath.row]
        }
    }
    

    items 似乎是一个数组,但didSelectItemAt 只考虑当前索引路径。所以要么声明一个item,要么创建一个数组

    destination.items = [guys[indexPath.row]]
    

    另一个解决方案是确实使用indexPathsForSelectedItems,但您必须以某种方式解开可选选项并将索引路径映射到行并获取给定索引处的项目。

    【讨论】:

      【解决方案2】:

      你能试试下面的代码吗?

      if let index = collectionView.indexPathsForSelectedItems?.first?.row {
          destination.items = guys[index]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多