Here's the background: I have a UICollectionView which contains UITableView as its cell. Whenever I select UITableViewCell, I want to know which UICollectionViewCell the action is from.
But I fail to get the right index of UICollectionViewCell. As the code below.
First, in the init method, I register my custom cell.
[self registerClass:[QuestionCVCell class] forCellWithReuseIdentifier:QuestionCVCellIdentifier];
Then, in the 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;
}
The log is in mess, and not same as the right index I meant. I guess it has something to do with the dequeueReusableCellWithReuseIdentifier
?
In code above, cell.index is passed to QuestionCVCell
, which contains a tableview. I add a notification poster in its didSelectRowAtIndexPath:
delegate to let main controller know that the select is from which collectionview cell.
This is the whole process of my problem.
I've searched for similar questions in Google, and find some solutions like these:
- Get the index from delegate of UIScrollView;
- Get the index by the point you touch, using
indexPathForItemAtPoint:
or similar methods. - Someone said that it should be indexPath.item in collectionview instead of indexPath.row, so I logged both of them and didn't see the difference.
So my question is:
Is there a direct way to get the correct index of UICollectionView? Why I get the right model by
[_questions objectAtIndex:indexPath.item]
but the wrong index byindexPath.item
?Is there any better way to let main controller know that the tableview cell select action belong to which collectionview cell?
If you find any problem or mistake in my solution, please do let me know.
Thanks in advance if anyone could help with it.