我有一个集合视图,我希望它是n个部分,每个部分有10个单元格,我的问题是:也许n等于35,在这个例子中,我想显示3个单元格和最后一个部分,只有5个单元格。
发布于 2019-05-28 10:23:18
如果数组计数为35 return count/10,如果count%10为0,则在numberOfSections方法中返回count/10+1
在numberOfItemsInSection方法中,将电流段乘以10,减去计数。返回最小值为10或减去值
在cellForItemAt方法中,用10乘区段并添加行以获得数组索引
class ViewController: UIViewController, UICollectionViewDataSource {
var arr = Array(1...35)
func numberOfSections(in collectionView: UICollectionView) -> Int {
return (arr.count/10) + (arr.count%10 == 0 ? 0 : 1)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return min(10,arr.count - (10*section))
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? Cell
let currentStr = arr[(indexPath.section*10)+indexPath.item]
cell?.label.text = "\(currentStr)"
return cell!
}
}

发布于 2019-05-28 10:07:54
您可以简单地实现UICollectionViewDataSource方法,并根据每个section配置cells的数量。
let n = 35 //It specify the total elements count
func numberOfSections(in collectionView: UICollectionView) -> Int {
return n/10
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case (n/10):
return (n % 10)
default:
return 10
}
}在上面的代码中,collectionView将有
last section的细胞other sections的10个细胞请澄清您的条件,以便我可以相应地更新代码。
发布于 2019-05-28 19:37:58
可以使用此扩展将数组拆分为块。
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}如果计数为35 -> 10,10,10,5
如果计数为30 -> 10,10,10
如果计数为29 -> 10,10,9
然后在集合视图委托方法中使用二维数组。
class ViewController: UIViewController, UICollectionViewDataSource {
let array = Array(1...35)
lazy var chunkedArray = array.chunked(into: 10)
func numberOfSections(in collectionView: UICollectionView) -> Int {
return chunkedArray.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return chunkedArray[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
print(chunkedArray[indexPath.section][indexPath.item])
return cell
}
}

https://stackoverflow.com/questions/56339689
复制相似问题