首页 > 解决方案 > UICollectionView didSelectItem 返回错误的索引路径

问题描述

UICollectionView在我的应用程序中使用 a 让用户在这些城市的几个城市和餐馆之间进行选择。

首先,我将加载包含餐厅的城市。

cities = RestaurantsLoader.cities()

然后我会UICollectionView用它们填满。

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
    }
}

然后显示它们(用 aUILabel因为我还没有开始创建自定义单元格)

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
    }
}

现在,我实现didSelectItemUICollectionView.

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

但是,这个 indexPath 几乎总是关闭。当我按下位于 section: 1, item: 25 的单元格时,它将打印 section: 2, item: 0 例如。我觉得这很奇怪,以前从未真正遇到过这样的事情。我究竟做错了什么?或者我该如何解决这个问题?

标签: iosswiftuicollectionview

解决方案


您必须使用“indexPath.item”


推荐阅读