Итак, у меня есть UICollectionView, основанный на массиве numOfPlayers. Я настроил его так, чтобы максимальное количество игроков было 7. Я хотел бы, если возможно, для последней ячейки UICollectionView добавить еще одну ячейку (или игрока) в массив. Затем, если это 7-й игрок, он просто становится другим игроком.

Я хотел бы уменьшить количество необходимых кнопок. Любая помощь или указатель в правильном направлении.

Максимум, который я хочу в массиве, равен 7. Есть проверки и противовесы, чтобы убедиться, что он не превышает 7. Также есть проверки на случай, если я перейду больше 8.

Массив начинается с минимум 3 элементов. Итак, в представлении коллекции отображаются 3 элемента, а затем четвертый - ячейка, к которой нужно добавить четвертый. После того, как 4-я ячейка добавлена ​​в массив, 5-я ячейка будет добавлена ​​ячейкой. Повторить. Когда в массиве 6 элементов, в седьмую ячейку нужно добавить элемент. После добавления 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
}

Цвет фона - это просто место для просмотра ячеек. Убедившись, что они генерируют правильный путь.

0
Micheal 15 Окт 2020 в 20:37

1 ответ

Лучший ответ
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 и убедиться, что вы изменили свою логику в зависимости от того, является ли выбранная ячейка игроком или ячейкой для добавления нового игрока

1
Nathan Walsh 15 Окт 2020 в 18:08