Swift UICollectionView,最后一个单元格添加另一个单元格

Swift UICollectionView, last cell adds another cell

所以我有一个基于 numOfPlayers 数组的 UICollectionView。我将其设置为玩家的最大数量为 7。如果可能的话,我希望 UICollectionView 的最后一个单元格向数组添加另一个单元格(或玩家)。然后,如果它是第 7 个玩家,它就会变成另一个玩家。

我想减少所需按钮的数量。任何帮助或正确方向的一点。

数组中我想要的最大值是 7。有检查和平衡以确保它不会超过 7。还有检查以防我超过 8。

数组从最小的 3 个元素开始。 所以在集合视图中显示了 3 个元素,然后第 4 个是要添加第 4 个的单元格。将第 4 个添加到数组后,第 5 个单元格将添加单元格。重复。当数组中有 6 个元素时,第 7 个单元格应添加一个元素。添加第 7 个元素后,它应该只显示 7 个单元格,而且只有 7 个。

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "playerCell", for: indexPath) as! APLCollectionViewCell
    cell.backgroundColor =  .green
    
    cell.playerLvlLbl.text = "\(apl.numOfPlayers[indexPath.row])"
    
    return cell
}

背景颜色只是用于查看单元格的占位符。确保它们以正确的方式生成。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if(apl.numOfPlayers.count < 7) {
       return apl.numOfPlayers.count + 1 //add one here for your cell that will be used to add a player
    }
    return apl.numOfPlayers.count // you could add more checks here to make sure it doesn't go over 7 but in your post you said you already have checks to make sure numOfPlayers is never more then 7 so probably just send this if the inital if fails
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if(apl.numOfPlayers.count < 7 && indexPath.row == (apl.numOfPlayers.count + 1)) { // first check if the add cell is present and check if the cell this is laying out is the last cell in the list
       //write code here to create a "add cell" something like below
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addCell", for: indexPath) as! AddPlayerCollectionViewCell
        cell.backgroundColor =  .red
    
        cell.textLabel.text = "Add a new player"
    
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "playerCell", for: indexPath) as! APLCollectionViewCell
        cell.backgroundColor =  .green
    
        cell.playerLvlLbl.text = "\(apl.numOfPlayers[indexPath.row])"
    
        return cell
    }
}

那么您还应该重写 didSelectItemAtIndexPath 方法,并确保根据所选单元格是播放器还是添加新播放器的单元格来更改逻辑