如何按索引从 UICollectionView 传递数据

how can I pass a data from a UICollectionView indexwise

我之前从 tableView 传递了一些数据,如下所示:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if( segue.identifier == "productList_to_detail" ) {

        let VC1 = segue.destination as! ShopItemVC
        if afData == 1 {
          if let indexPath = self.tableView.indexPathForSelectedRow {
                let productIdToGet = sCategory[indexPath.row]
                VC1.product_id = productIdToGet.product_id
            }
        }
    }
}

如您所见,当我点击特定的 Cell 时,它会从中获取一些数据并传递与 Cell 相关的数据.现在我想做同样的事情,但要使用 CollectionView。当我点击 CollectionView 的特定 item 时,我想从中获取一些值并将其传递给 segue。我怎样才能做到这一点 ?

要在 prepare(for:sender:) 方法中访问 collectionView 的选定单元格数据,这取决于您在故事板中创建 segue 的方式。

  • 如果 Segue 是从 UICollectionViewCell 创建到目标 ViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        if( segue.identifier == "productList_to_detail" ) {
    
            let VC1 = segue.destination as! ShopItemVC
            if let cell = sender as? UICollectionViewCell,
               let indexPath = self.collectionView.indexPath(for: cell) {
    
                  let productIdToGet = sCategory[indexPath.row]
                  VC1.product_id = productIdToGet.product_id
            }
        }
    }
    
  • 如果 Segue 是从源 ViewController 到目标 ViewController 创建的。

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //Pass indexPath as sender
        self.performSegue(withIdentifier: "productList_to_detail", sender: indexPath)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        if( segue.identifier == "productList_to_detail" ) {
    
            let VC1 = segue.destination as! ShopItemVC
            if let indexPath = sender as? IndexPath {
    
                  let productIdToGet = sCategory[indexPath.row]
                  VC1.product_id = productIdToGet.product_id
            }
        }
    }