繁体   English   中英

通过将“ ID”作为参数发送,将数据从一个collectionView单元格快速传递到另一collectionview控制器中的数据4

[英]passing data from one collectionView cell to other collection view controller in swift 4 by sending “ID” as a parameter

我在Swift 4中有一个关于Collection View的查询。

我有一个集合视图,将其命名为Category-Collection-View-Controller 在此,每个类别都有一个唯一的ID,该ID来自后端。 当我单击特定类别时,它将导航到另一个名为SubCategories-CollectionView-Controller集合视图。 并显示“ Category-Collection-View-Controller”的所有信息。 请任何人向我解释我如何将来自后端的“ ID”作为参数传递给Alamofire函数。

您可以通过以下方式将数据从一个视图控制器传递到另一个:

  • 代表
  • Segue公司
  • 通知

我建议您使用segue,因为您必须在类别点击上执行segue操作。

编码示例:

  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

   // You can use a traditional push view controller method.
   //let id = dataSourceArray[indexPath.item]
   //let vc = self.storyboard?.instantiateViewController(withIdentifier: "SubCategories-CollectionView-Controller"") as! SubCategories-CollectionView-Controller
   //vc.id = id
   // self.navigationController?.pushViewController(vc, animated: false)

        // Get the category id and pass it through segue 
        performSegue(withIdentifier: "identifier", sender: id)
    }

prepare for segue方法时,您可以将此ID传递给下一个视图控制器。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identifier" {
        let senderID = sender as? Int
        let vc = segue.destination as? SubCategories-CollectionView-Controller
        vc.id = senderID
    }
}
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let id = dataArray[indexPath.item]
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SubCategories-CollectionView-Controller") as! SubCategories-CollectionView-Controller
        vc.id = id
        self.navigationController?.pushViewController(vc, animated: false)
}

这里dataArray是数据数组,通过它可以在Category-Collection-View-Controller中显示数据。 现在,当用户点击它时,您可以通过didselectitem方法获取数据,并将其传递给下一个控制器。

在CategoryCollectionViewController中声明ID,然后使用此ID提取子类别详细信息。

class CategoryCollectionViewController: UIViewController {
    var id : Int?

     override func viewDidLoad() {
         Almofire.FetchSubcategory(catid:id) {  catgorydata in
              subcategoryCollectionView.reloadData()
         }
     }
}

在您的categoryCollectionView控制器中,通过CollectionView didselect方法传递类别ID

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let categoryID = categoryArray[indexPath.row]
        let subcategorycontroller = SubCategoryController()
        subcategorycontroller.id = categoryID
        self.present(subcategorycontroller, animated: false, completion: nil)

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM