Question

I have a UICollectionView embedded in a scroll view: see picture

Each white square is a collection view cell. The user can scroll horizontally to reveal additional cells.

When the user clicks on a cell, I have created an animation which causes that cell to expand from its own center outward as a transition is made to a new view controller.

Here is the code:

//cell is selected:

//grab snapshot of cell
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
UIImage *cellImage = [self imageOfCollectionCell:cell]; 

//hold the snapshot in this dict    
NSMutableDictionary *cellImageDict = [[NSMutableDictionary alloc]init];
[cellImageDict setObject:cellImage forKey:SELECTED_INBOX_EMAIL_IMAGE];
[ViewControllerSnapShotDictionary sharedInstance].vcdict = nil;
[ViewControllerSnapShotDictionary sharedInstance].vcdict = cellImageDict; 

//get the center of the cell (HERE IS WHERE THE PROBLEM IS)
CGPoint cellCenter = CGPointMake(cell.center.x, cell.center.y);

//do the animation using the snapshot and cell center
[self startPinchingOutCellFromCenterPoint:cellCenter forTransitionTo:emailController withSnapShotImage:SELECTED_INBOX_EMAIL_IMAGE]; 

The code works fine, EXCEPT if the collection view has been scrolled. The animation requires that I know where the center of the cell is at the moment it is on screen, being touched and relative to the coordinates of the view I am looking at.

For example, if the collection view has not been scrolled, and I select the center cell of the above image, the center might return as:

cell.center.x = 490
cell.center.y = 374

However, if I do a scroll to the right, and then select the new center cell, I might get something like:

cell.center.x = 1770
cell.center.y = 374

My question is, is there either a better way to accomplish what I am trying to do, OR is there a way to get a handle on the center of the cell as it lies in its current position in self.view?

Was it helpful?

Solution

I think this is because the center coordinates are in the collectionView's coordinate system (which scrolls). You need to convert it to a coordinate system that doesn't scroll.

Try something like this:

CGPoint realCenter = [collectionView convertPoint:cell.center 
                                     toView:collectionView.superview];

What it does, is basically converts the center from the collectionView's coordinate system to it's parent which should be fixed (not scrolling).

You can even obtain the coordinate on the screen(window) by passing nil as parameter:

CGPoint realCenter = [collectionView convertPoint:cell.center 
                                     toView:nil];

It's up to you to decide to which coordinate you want to convert.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top