ios - 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
}
}
现在,我实现didSelectItem
了UICollectionView
.
extension RestaurantPickerViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath)
}
}
但是,这个 indexPath 几乎总是关闭。当我按下位于 section: 1, item: 25 的单元格时,它将打印 section: 2, item: 0 例如。我觉得这很奇怪,以前从未真正遇到过这样的事情。我究竟做错了什么?或者我该如何解决这个问题?
解决方案
您必须使用“indexPath.item”
推荐阅读
- angular - Angular 智能(容器)/哑(展示)组件架构、条件逻辑和传播输入
- javascript - 从 Bokeh 中的 NetworkX Graph 中获取选定的字形
- javascript - 通过 Mix 将 node_modules 导入 Laravel
- python - 使用列标题和索引值进行操作
- r - detach() v remove.packages()
- c# - ASP.NET Post Endpoint:正文中的数据模型与查询参数
- c++ - clCreateContextFromType 抛出异常
- python - Django:以编程方式在用户保存时添加组
- python - 编写一个函数,返回并打印列中所有值中的最大值
- .net-core - 为什么“项目路径”不可修改?