CollectionView部分

时间:2019-05-28 10:02:13

标签: swift uicollectionview

我有一个collectionview,我希望它是n个部分,其中每个部分都有10个单元格,我的问题是:也许n等于35,在这种情况下,我想显示3个具有10个单元格的部分,最后一节只有五个。

3 个答案:

答案 0 :(得分:2)

如果数组计数为35 return count/10,如果count%10为0,则在count/10+1方法中返回numberOfSections

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!
    }
}

enter image description here

答案 1 :(得分:1)

您可以简单地实现UICollectionViewDataSource方法,并根据每个collectionView(_:numberOfItemsInSection:)的{​​{1}}数量来配置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的(n%10)个单元格
  • last section的10个单元格

请明确您的条件,以便我可以相应地更新代码。

答案 2 :(得分:1)

您可以使用此扩展名将数组拆分为多个块

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]

然后在collectionview委托方法中使用二维数组

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
    }
}

enter image description here