Как программно настроить динамическое количество представлений коллекции в Swift c - PullRequest
0 голосов
/ 10 февраля 2020

У меня есть список многих Decks, который в основном имеет name и список Cards. Ниже приведена структура класса.

class Deck{
    var id:String
    var name:String
    var cards:[Card]

    init(id:String, name:String, cards:[Card]) {
        self.id = id
        self.name = name
        self.cards = cards
    }
}

class Card {
    var id:String
    var name:String

    init(id:String, name:String){
        self.id = id
        self.name = name
    }
}

Мне нужно иметь возможность создать по одному UICollectionView для каждой колоды, где каждая ячейка должна представлять кнопку с названием одной карты, и мне нужно возможность определить, какая кнопка ячейки нажата. Это означает, что мне нужно разрешить как динамическое c число UICollectionView (список колод), так и динамическое c число UICollectionViewCell (список карт). Обратите внимание, что я уже понимаю, как создать ячейки динамически и определить, какие кнопки ячейки были нажаты.

В целом, основная проблема заключается в том, что я не буду знать, сколько колод и, следовательно, сколько UICollectionViews мне нужно создать. Но, поскольку структура всех UICollectionViews одинакова, но содержит разные значения (т. Е. Количество ячеек, заголовок метки ячейки имеет разные значения), мне интересно, как можно динамически создавать UICollectionViews ( НЕ UICollectionViewCells ) и заполнить их колодами из списка, например колоды: [Колода]

Спасибо большое! Изображение внизу показывает примерно то, что я хотел бы сделать.

enter image description here

Ответы [ 3 ]

1 голос
/ 10 февраля 2020

По-прежнему неясно, нужна ли вам коллекция объектов UICollectionView, или вы можете использовать несколько разделов в одном представлении коллекции. В любом случае, если вам нравятся множественные виды коллекций, просто создайте коллекцию или табличное представление, отображающее список колод, и поместите представление коллекции для колоды в ячейку.

class DeckCell: UICollectionViewCell { // or class DeckCell: UITableViewCell
    var deck: Deck = .empty

    @IBOutlet weak var collectionView: UICollectionView!
}

extension DeckCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.deck.cards.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath)
        cell.card = self.deck.cards[indexPath.row]
        return cell
    }
}
0 голосов
/ 10 февраля 2020

Вот простое решение для вас.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //number of items in Decks Array will be its count
    if collectionView == dockCollectionView {
        return Decks.count  //It will tell the collection view how much cell will be there
    }
    if collectionView == cardsCollectionView {
        return Cards.count
    }
}

//Setup your resuable cell here
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //Setup for Dock CollectionView
    if collectionView == dockCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Dock Cell Identifier Name", for: indexPath)
        // This will return a each item name from the item list and display in to a cell
        cell.textLabel.text = Decks[indexPath.row].name
        return cell
    }
    //Setup for Cards CollectionView
    if collectionView == cardsCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Cards Cell Identifier Name", for: indexPath)
        // This will return a each item name from the item list and display in to a cell
        cell.textLabel.text = Cards[indexPath.row].name
        return cell
    }
}

//Now get to know which cell is tapped
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if collectionView == dockCollectionView {
        print(Decks[indexPath.row].name)
    }
    if collectionView == cardsCollectionView {
        print(Cards[indexPath.row].name)
    }
    // Here you write a code when user select a particular cell
}
0 голосов
/ 10 февраля 2020

У вас уже есть решение, у вас есть список, в котором у вас есть элементы, поэтому вы должны реализовать их динамически, поэтому вам просто нужно подсчитать количество элементов в списке.

Так что для этого вы используете items.count in fun c: -

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Cell Identifier Name", for: indexPath)
    // This will return a each item name from the item list and display in to a cell
    cell.textLabel.text = item[indexPath.row]
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // Here you write a code when user select a particular cell
}
...