ios - 独立填充 Collection View 的每个部分 Swift

标签 ios swift uitableview collections uicollectionview

我有一个嵌入在 TableView 中的 Collection View ,因此它可以垂直和水平滚动。它有四个部分,今天、本周、本月、今年。我无法理解如何用自己的数据填充每个部分。现在我正在使用下面的代码来填充 Collection View ,但所有部分都具有相同的数据。如何用自己的数据填充每个部分?

因此,如果我有一组今天的图像、一组本周的图像、一组本月的图像和一组今年的图像,我如何将其部分中的 ImageView 设置为相应数组中的项目?所以今天应该有 todayImageArray 中的图像,本周应该有 thisWeekImageArray 中的图像等等。

另外,我将 Collection View 的委托(delegate)和数据源设置为 TableView 。

非常感谢任何帮助!

let images: [[UIImage]] = [
    [image_1, image_2, image_3, image_4],
    [image_5, image_6, image_7, image_8],
    [image_9, image_10, image_11, image_12],
    [image_13, image_14, image_15, image_16]
]    

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return images.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images[section].count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell

    cell.imageView.image = images[indexPath.section][indexPath.row]

    return cell
}

最佳答案

您需要一个结构化数据源。目前,从您的代码来看,您似乎有一个名为 images 的数组,并且您正在使用它来提供项目数量并更新单元格内容。但是,如果您需要单独的部分,则需要对数据源进行建模,并为数据源和 collectionView 中的委托(delegate)方法提供逻辑响应。

示例简单数据源:

let simpleDataSource: [[UIImage]] = [
  [image1, image2],
  [image3, image4],
  [image5, image6]
]

在 collectionView 方法中使用它的示例:

func numberOfSections(in collectionView: UICollectionView) -> Int {
  return simpleDataSource.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  return simpleDataSource[section].count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell
  cell.imageView.image = simpleDataSource[indexPath.section][indexPath.row]
  return cell
}

您还应该通读 documentation for UICollectionView .

关于ios - 独立填充 Collection View 的每个部分 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42283467/

相关文章:

swift - 如何删除条形图上的这些值

ios - 水平滚动时如何防止 UITableView 内容被剪切?

iOS:使用 Swift2 删除 .DocumentDirectory 中的文件

iphone - 如何通过iphone app中的代码获取用户的当前位置?

ios - 应用程序从后台终止后是否可以继续下载文件

ios - 相机预览层使按钮不可见

ios - 闭包语法中的 Swift weak Self

ios - UINavigationController 代码推送到 UIViewController 无法正常工作

ios - 如何在所有单元格周围的空白处接收 UICollectionView 上的触摸

ios - 如何将弱引用对象存储在数组中,objc中的字典?