首页 > 解决方案 > Swift UICollectionView,最后一个单元格添加另一个单元格

问题描述

所以我有一个UICollectionView基于numOfPlayers数组的。我已将其设置为最大玩家数为 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
}

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

标签: swiftuicollectionview

解决方案


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 方法并确保根据所选单元格是玩家还是要添加新玩家的单元格来更改逻辑


推荐阅读