代码之家  ›  专栏  ›  技术社区  ›  Kaveh Naseri

将参数从CollectionViewController传递到CollectionViewCell

  •  -1
  • Kaveh Naseri  · 技术社区  · 8 年前

    我试图在单击某个类别后显示产品列表。我将类别ID(rowid)发送到productListController,在那里我可以访问rowid。

    我想将rowid发送到我的productListCell类,并将rowid传递到我的setViews()中的fetchproduct(rowid:int)。

    到目前为止,我已经尝试过NotificationCenter和Protocol类,我可以找到我要查找的结果。

    产品单元格列表.swift

    class ProductListCell : BaseCell ,UICollectionViewDataSource,  UICollectionViewDelegate,UICollectionViewDelegateFlowLayout
    {
        let cellId = "cellId"
        var products = [Product]()
        weak var delegate: ProductCellDelegate?
    
        override func setupViews() {
            super.setupViews()
    
            var receivedRowId = getRowId() // here is the problem - i can't get the rowid from productlistcontroller
    
            fetchProduct(rowId: receivedRowId)
    
            addSubview(collectionView)
            addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView)
            addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView)
    
            collectionView.register(ProductCell.self, forCellWithReuseIdentifier: cellId)
        }
    
        func fetchProducts(rowId: Int){
    
            ApiServiceProduct.sharedInstance.fetchProductsList(rowId: rowId) { (products:[Product]) in
                self.products = products
                self.collectionView.reloadData()
            }
        }
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Warren Burton    8 年前

    你的架构完全错误。以最友善的方式,你需要找到 UICollectionView 辅导的。找一个,有很多。

    集合视图单元格不应管理其父集合视图。

    简单的概述。

    enter image description here

    • 你的 ViewController 将管理 ui集合视图 实例。

    • 会有一个对象采用 UICollectionViewDatasource 协议。

    • 这个 视图控制器 将该对象分配给 datasource 集合视图上的属性。

    • ui集合视图 会打电话的 collectionView(_: UICollectionView, cellForItemAtIndexPath:) 数据源

    • 该方法将返回 UICollectionViewCell . 在你的例子中 ProductListCell .

    • CollectionView(:uiCollectionView,CellForItemAtindexPath:) 是设置 rowID 属性。一个单元可以被 dequeueReusableCell(withReuseIdentifier:, for:) 方法。你不应该假设 小精灵 将保持不变。

    这比我说的要多,但它应该能让你开始。祝你好运。

        2
  •  0
  •   Scott McKenzie    8 年前

    我不太明白你的问题,但是 UICollectionView 通过 UICollectionViewDelegate func collectionView(UICollectionView, didSelectItemAt: IndexPath) 这可能是执行此任务的理想位置,尤其是在rowid和类别相同的情况下。

    推荐文章