noxo.
noxo.

Reputation: 126

Find in which row of a tableView is a CollectionView

I'm asking for your help because I blocked with something in my Swift App. I would like to parse an array with some meals. My array is the next one:

let meals_list: [[String]] = [
                                 ["breakfast", "snack_1", "pre_intra_post", "lunch", "snack_2", "diner"], 
                                 ["breakfast", "snack_1", "lunch", "snack_2", "diner"]
                             ]

As you can see, there are 6 items in the first part, and 5 items in the second one.

These meals are going to be displayed in a horizontal CollectionView.

Each CollectionView needs to be in a table view.

So, I would like to create 6 cards in my first collection view And 5 cards in my second collection view.

Here is how I manage everything

//Manage meals content
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0{
            return 6
        } else {
            return 5
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! Meal_vc_cell

        return cell
    }



    //Manage day type content (train/rest)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "food_plan_cell", for: indexPath) as! FoodPlanCell

        if (indexPath.row == 0){
            cell.meals_day_type.text = "Vos repas les\r\njours d'entraînement".uppercased()
        } else {
            cell.meals_day_type.text = "Vos repas les\r\njours de Repos".uppercased()
        }

        return cell
    }

    private func tableView(tableView: UITableView,
        willDisplayCell cell: UITableViewCell,
        forRowAtIndexPath indexPath: NSIndexPath) {

        guard let tableViewCell = cell as? FoodPlanCell else { return }

        tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
    }

Upvotes: 0

Views: 162

Answers (1)

Celeste
Celeste

Reputation: 1577

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as? Meal_vc_cell else {
       fatalError("The dequeued cell is not an instance of Meal_vc_cell")
    }

    cell.meal.text = meals_list.[indexPath.section][indexPath.item]

    return cell
}

Upvotes: 1

Related Questions