ios - 由不等部分分隔的数组中的二维数组
问题描述
我有一个带有 40 个单元格等的 UICollectionView。滚动时我请求广告,如果有,我应该在前 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) 等等
我怎样才能做到这一点 ?
解决方案
我认为这会做你想要的。它使用prefix
anddropFirst
删除项目,直到它使适当的节数减 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))
输出:
[[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]]
推荐阅读
- elasticsearch - ElasticSearch:在包含文档的日期范围中查找不同日期的最佳方法是什么?
- kendo-ui - kendo-ui angular 6 如何使用模板自定义网格的列
- azure-devops - 如何为 repo 的 wiki 创建构建管道?
- angular - canActivated 保护的返回值错误
- android - 为什么 Android Studio 显示 Code xml 像“� �”
- angular - angular 6 / ngx-translate 和动态 devextreme dxDatagrid 列
- node.js - Node.js“无法读取未定义的属性'长度'
- azure - Azure Durable Functions - 无法更改任务中心名称以支持并行版本控制
- linux - 安装 RPM 不会运行 .spec 中列出的所有 %install 操作
- azure - Azure 重置功能键?