繁体   English   中英

由不等部分分隔的数组中的二维数组

[英]Two-dimensional array from array separated by unequal sections

我有一个 UICollectionView 有 40 个单元格等。滚动时我请求广告,如果有,我应该在前 5 个单元格之间显示它。 然后,当我向前滚动时,我应该请求第二个,并在第二个 5 单元格之间显示它。 例如,我滚动到第 4 个单元格,请求广告,它来了,我在第 5 个和第 6 个单元格之间显示它,等等。

我决定为单元格之间的那些广告创建部分。 现在我需要重新组织我的元素数组。

前:

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        items.count
}

后:

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


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

我的splitPublications数组是一个二维数组,我需要根据广告数组计数来组织它。 所以最后我应该得到这样的东西:

第 1 节 - (0,1,2,3,4)

第 2 节 - (5,6,7,8,9)

*如果只有 2 个广告

第 3 节 - (10,11,12,13,14,15,16,17,18,19,20...40) 等等

我怎样才能做到这一点?

我认为这会做你想要的。 它使用prefixdropFirst来删除项目,直到它使适当数量的节数减 1,然后将剩余的项目放在最后一个节中:

func makeSections<T>(items: [T], numberPerSection: Int, maxSectionCount: Int) -> [[T]] {
    var items = items
    var result = [[T]]()
    
    while !items.isEmpty && result.count < maxSectionCount - 1 {
        result.append(Array(items.prefix(numberPerSection)))
        items = Array(items.dropFirst(numberPerSection))
    }
    
    if !items.isEmpty {
        result.append(items)
    }
    
    return result
}

例子:

let items = Array(0...40)

// If we have 2 ads, we will have 3 maximum sections
print(makeSections(items: items, numberPerSection: 5, maxSectionCount: 3))

Output:

 [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM