user4992124
user4992124

Reputation: 1594

UICollectionView didSelectItem returning wrong indexpath

I'm using a UICollectionView in my app to let the user choose between a couple of cities and restaurants in these cities.

First, I'll load the cities with the restaurants in them.

cities = RestaurantsLoader.cities()

I'll then fill up the UICollectionView with them.

extension RestaurantPickerViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 40, height: 40)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }
}

And then display them (with a UILabel because I haven't gotten to creating a custom cell yet)

extension RestaurantPickerViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cities[section].restaurants.count
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return cities.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "normalCell", for: indexPath)  
        cell.viewWithTag(123)?.removeFromSuperview()

        let label = UILabel(frame: cell.bounds)
        label.text = cities[indexPath.section].restaurants[indexPath.item].name
        label.textAlignment = .center
        label.tag = 123
        cell.addSubview(label)

        return cell
    }
}

Now, I implemented the didSelectItem function of the UICollectionView.

extension RestaurantPickerViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath)
    }
}

However, this indexPath is almost always off. When I press a cell located at section: 1, item: 25, it'll print section: 2, item: 0 for example. I find this really odd and haven't really come across something like this before. What am I doing wrong? Or how can I fix this?

Upvotes: 1

Views: 840

Answers (1)

Pedro E. Waquim
Pedro E. Waquim

Reputation: 11

You have to use "indexPath.item"

Upvotes: 1

Related Questions