【问题标题】:Changing the DataSource of UICollectionView in Swift在 Swift 中更改 UICollectionView 的数据源
【发布时间】:2015-07-13 10:11:48
【问题描述】:

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

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

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

【问题讨论】:

  • 你试过改变collection view的数据源吗?
  • 我该怎么做?因为我的 dataSource 是我的 [Product] 数组,它设置了行和单元格值,所以我无法将数组的类型更改为我的类别。有没有办法将 dataSource 和其他所有内容设置为不同的值?

标签: swift uicollectionview


【解决方案1】:

是的,您可以通过添加一些指示器来实现它,当用户键入类别按钮时您将更改这些指示器,例如 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 并调用 reload data 方法。

如果您有更多数据源/委托方法,您也应该添加条件。

【讨论】:

  • 谢谢格雷格。不知道为什么我从来没想过这么简单的解决方案
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    相关资源
    最近更新 更多