这是背景:我有一个UICollectionView,其中包含UITableView作为其单元格 . 每当我选择UITableViewCell时,我想知道该动作来自哪个UICollectionViewCell .
但我无法获得正确的UICollectionViewCell索引 . 如下面的代码 .
首先,在init方法中,我注册了我的自定义单元格 .
[self registerClass:[QuestionCVCell class] forCellWithReuseIdentifier:QuestionCVCellIdentifier];
然后,在UICollectionViewDataSource中 .
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = nil;
cell = (QuestionCVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:QuestionCVCellIdentifier forIndexPath:indexPath];
if (_questions && _questions.count > 0) {
((QuestionCVCell *)cell).model = [_questions objectAtIndex:indexPath.item];
((QuestionCVCell *)cell).index = indexPath.item;
NSLog(@" %ld, %ld",(long)indexPath.item, (long)indexPath.row);
}
return cell;
}
日志很乱,与我指的正确索引不一样 . 我想这与 dequeueReusableCellWithReuseIdentifier
有关?
在上面的代码中,cell.index传递给 QuestionCVCell
,其中包含一个tableview . 我在其 didSelectRowAtIndexPath:
委托中添加了一个通知海报,让主控制器知道select是来自哪个collectionview单元格 .
这是我的问题的整个过程 .
我在谷歌搜索过类似的问题,并找到一些类似的解决方案:
-
从UIScrollView的委托中获取索引;
-
使用
indexPathForItemAtPoint:
或类似方法获取您触摸的点的索引 . -
有人说它应该是collectionview中的indexPath.item而不是indexPath.row,所以我记录了它们并没有看到差异 .
So my question is:
-
有没有直接获取UICollectionView的 correct index 的方法?为什么我通过
[_questions objectAtIndex:indexPath.item]
获得正确的模型,但indexPath.item
的错误索引? -
有没有更好的方法让主控制器知道tableview单元格选择操作属于哪个collectionview单元格?
-
如果您在我的解决方案中发现任何问题或错误,请告诉我 .
如果有人可以提供帮助,请提前致谢 .
3 回答
我给你样本集合视图代码 . 它可以帮助你获得索引 .
在viewDidLoad中
在CollectionView数据源方法中
在Collection View Delegate方法中
而不是使用indexPath.row在UICollectionView中使用indexPath.item . 它会给你正确的索引 .
NSIndexpath.item vs NSIndexpath.row
使用委托模式来实现此目的 .
i)在CollectionView数据源方法中,将单元格标记设置为indexPath.row
ii)在QuestionCVCell类中创建自定义委托
iii)在tableView中,didSelectRowAtIndexPath方法调用委托方法
iii)在ViewController类中采用协议并添加委托方法 .
现在,只要选择了表行,它就会在ViewController类中使用集合视图索引调用tableSelectedWithIndex方法