在 Swift 中更改 UICollectionView 的数据源

Changing the DataSource of UICollectionView in Swift

我正在设计一个显示我数据库中所有产品的 UICollectionView。当用户打开 collectionView 时,会在自定义 CollectionViewCell 中显示从我的 [Product] 数组填充的所有产品。

我的产品 class 有一个 category 属性,我希望用户能够点击它,然后重新加载显示类别列表的 collectionView,供用户过滤数据。类似于 iOS 照片应用程序,可以按相册查看照片,但我更希望它在所有照片上启动。

有没有办法在不实现第二个 CollectionViewController 的情况下做到这一点?

是的,您可以通过添加一些指示器来实现它,当用户键入类别按钮时您会更改这些指示器,例如 bool 变量:

var showCategory = false

并且在您需要检查条件的每个数据源/委托方法中,例如:

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    if (showCategory) {
        return 10 // your logic to display data for categories
    } else {
        return 15 // your logic to display data for non categories
    }
  }


  override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if (showCategory) {
        return 10 // your logic to display data for categories
    } else {
        return 15 // your logic to display data for non categories
    }
  }

  override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell

    // Configure the cell
    if (showCategory) {
        // your logic to display data for categories
    } else {
        // your logic to display data for non categories
    }
    return cell
  }

请记住,当您想要显示类别时,您应该更改数据源,将 showCategory 变量设置为 true 并调用重新加载数据方法。

如果您有更多 datasource/delegate 方法,您也应该添加条件。

按照 Arsian Asim 的建议,更改集合视图的数据源,然后在 CollectionView

上调用 reloadData