【问题标题】:how can I pass a data from a UICollectionView indexwise如何从 UICollectionView indexwise 传递数据
【发布时间】:2017-01-31 04:51:45
【问题描述】:

我之前从 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 传递它。我怎样才能做到这一点 ?

【问题讨论】:

    标签: uitableview swift3 uicollectionview uicollectionviewcell


    【解决方案1】:

    要在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
              }
          }
      }
      

    【讨论】:

    • 哦,帮助了@NiravD
    • @ArafinMacRussell 欢迎朋友 :)
    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2014-07-09
    • 2011-04-04
    • 2020-12-29
    • 2020-08-01
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多