ios - UICollectionView 从左到右读取多行

标签 ios swift uicollectionview uicollectionviewlayout

我正在创建一个启用分页并从左向右滚动的UICollectionView。我正在使用 NSFetchedResultsController 从 CoreData 检索结果,这意味着它使用 Collection View 部分而不是行。 Collection View 有 2 行,因此如下图所示(顺序为顶行、底行、顶行、底行等):

enter image description here

但是,我需要 Collection View 从左到右阅读,如以下两个屏幕截图:

enter image description here enter image description here

您能告诉我如何在 Swift 中做到这一点吗?

最佳答案

我要做的是:

1) 按照与现在相同的方式对数据进行排序,以便您的 Collection View 如下所示:

---------
|0|2|4|6|
---------
|1|3|5|7|
---------

2) 在 Collection View 数据源的 cellForIndexPath 方法中返回正确的元素,以便 Collection View 变成这样:

---------
|0|1|2|3|
---------
|4|5|6|7|
---------

为此,您可以使用以下逻辑:

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var elementIndex: Int!
    if indexPath.row % 2 == 0 {
        // 0 / 2 = 0
        // 2 / 2 = 1
        // 4 / 2 = 2, etc
        elementIndex = indexPath.row / 2
    }
    else {
        // (1 / 2) + round(8.0 / 2.0) = 4
        // (3 / 2) + round(8.0 / 2.0) = 5
        // (5 / 2) + round(8.0 / 2.0) = 6, etc
        elementIndex = (indexPath.row / 2) + Int(round(Double(elements.count) / 2.0))
    }

    // Dequeue your cell
    // let cell = ...

    cell.element = elements[elementIndex]
    return cell
}

基本上,这应该以正确的顺序返回您的元素。

关于ios - UICollectionView 从左到右读取多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323564/

相关文章:

arrays - 如何使用数组更改多个变量而不是值?

ios - 仅显示一个位置权限警报

ios - 为什么我的 collectionViewCell 显示异常行为?

ios - 如何在 ios 中将数据从一个 View Controller 传递到另一个 View Controller

iphone - UIButton - 编程创建问题

ios - 室内导航(也许是 MapBox?)

Swift:被 Signal 4 终止

ios - 如何更新自动调整表格 View 高度?

iOS * 单元性能 : Autolayout vs Frame?

ios - ActivityIndi​​cator没有显示在CollectionViewCell上