3
votes

I would like to scroll collection view to some offscreen cell without animation and get position of that cell after scrolling. The problem is that collection view scrolls correctly (visually) but cell frame remains offscreen. Here is my code:

NSIndexPath *path = [fetchedResultsController indexPathForObject:objectInCollection];
[collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
[collectionView layoutSubviews]; // or 'layoutIfNeeded', doesn't matter
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:path];
cellFrame = [cell.superview convertRect:cell.frame toView:nil]; // still not refreshed

I can propose that collection view applies scrolling not immediately, so I would like to find approach to apply the scrolling.

--- UPDATE ---

The collection view is in previous view controller (so I scroll it from code and then pop visible view controller).

Cell frame remains offscreen even in viewDidAppear: method of previous view controller. To be exact, [cell.superview convertRect:cell.frame toView:nil]; returns frame without contentOffset of collection view. So CGRectOffset([cell.superview convertRect:cell.frame toView:nil], 0, -collectionView.contentOffset.y) returns correct cell frame on screen.

3
I don't know if I understood your problem correctly, but you ARE supposed to get the same frame for a cell even after scrolling. Scrolling will not change the frames of the subviews; only the contentOffset should change. Or are you trying to get the frame in the UICollectionView's superview coordinates?John Estropia

3 Answers

3
votes

As i can understand from your problem statement, you want to set the some cell which is out of the view to visible state.

The cells are placed at the same position when the UICollectionView calculates

  • (void)prepareLayout
  • (void)layoutAttributes.. methods.

The frames of the collection cells are fixed till the invalidateLayout or reloaddata is called. Just you have to work around with the contentOffset of the collectionview. Just get the frame of cell and set the contentOffset so the your frame of cell is visible on the screen. Hope it helps.

0
votes

The cell frame should be correct and I don't think you need to use convertRect at all.

cellFrame = cell.frame;

However, you probably have to do this after the collection view loads. Call [collectionView reloadData] first.

There is also a layoutAttributesForItemAtIndexPath: method that has the attributes for that cell. You can call this on the indexPath and get the attributes that way.

0
votes

Try changing scroll position to UICollectionViewScrollPositionBottom, this works for me -

[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];