如何在多个collectionView部分中使用单个数组?

时间:2019-02-03 13:01:05

标签: ios swift uicollectionview

我有一个包含游戏信息的数组。我的Json页面中有12个项目。我确实创建了具有3行的4个部分。它在每个部分中重复数组的前3个项目。

Screenshot from app

我想那样使用;

总项目数= 12

  1. 部分= 1 2 3
  2. 部分= 4 5 6
  3. 部分= 7 8 9
  4. 部分= 10 11 12

我该怎么做?在此先感谢:)

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


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "lastAddedCell", for: indexPath) as! lastAddedCell

        cell.gameName.text = name[indexPath.row]
        cell.gameImage.sd_setImage(with: URL(string:resimUrl[indexPath.row]))

    return cell
}

2 个答案:

答案 0 :(得分:1)

我认为这不是一个好主意。我宁愿通过创建节管理器来单独创建节,而不是从同一数组中进行创建。但是,如果您想按照现在的方式进行操作。这是一个简单的解决方法:

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


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "lastAddedCell", for: indexPath) as! lastAddedCell
    let index = indexPath.row + (indexPath.section * 3) // The index is then based on the section which is being presented
    cell.gameName.text = name[index]
    cell.gameImage.sd_setImage(with: URL(string:resimUrl[indexPath.row]))

    return cell
}

答案 1 :(得分:0)

请在下面考虑此情况并予以实施,

var array = [1,2,3,4,5,6,7,8,9,10,11,12]

//Statcially you can slice them like this

    var arr2 = array[0...2] {
        didSet {
            //reload your collection view
        }
    }
    var arr3 = array[3...5]
    var arr4 = array[6...8]
    var arr5 = array[9...array.count - 1]

上面您手动为每个dataSource切片了UICollectionView,但是问题是这确实有风险,最终会导致Index Out of Range崩溃,因此我们通过循环动态地对数组进行切片它使用+3索引范围内的每个元素的索引附加到新的UICollectionView数据源。

    // loop thru the main array and slice it based on indexes
for(index, number) in array.enumerated() {
    if 0...2 ~=  index { // if in range
        arr2.append(number)
    } else
    if index <= 5 {
        arr3.append(number)
    } else
    if index <= 8 {
        arr4.append(number)
    } else
    if index <= 11 {
        arr5.append(number)
    }
}

最后:在您的numberOfItemsInSection中检查UICollectionView并设置返回其数据源,例如

if collectionView = myMainCollectionView { 
return arr3.count 
}

cellForItemAt

也是一样

注意:确保您的dataSource数组最初为空,

let arr2: [Int] = [] { 
 didSet{
  //reload your collectionView 
 }
}
相关问题