Joe
Joe

Reputation: 3961

Returning to the same scroll position of UICollectionView after tapping a cell

I have a UICollectionView that is populated with all photos from the devices photo library. After a cell (photo) is tapped, it segues to a view controller that allows for editing. On this view, there is an "Add Photo" button to return the user back to the UICollectionView (to select another photo). I need for the scroll position to "focus" the previous tapped cell in the center of the view without any animations or jumping.

I have tried saving the tapped indexPath as a variable, then on viewDidAppear, scroll to that indexPath with scrollToItemAtIndexPath. The problem is I can't figure out how to update a variable (to save indexPath) on cell tap. I tried this in didSelectItemAtIndexPath, but the value never actually saves.

var cellTappedIndexPath = Int()

Inside didSelectItemAtIndexPath:

cellTappedIndexPath = indexPath.row

The value for cellTappedIndexPath never saves.

Just for testing out scrollToItemAtIndexPath, I have added the following to viewDidAppear:

customViewCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 25, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: false)
// 25 is just a number I have set for testing. Ultimately, I would like this to be the saved indexPath of the last tapped cell.

This causes the collectionView to "jump" to cell 25 once it's fully loaded. If I set animated to true, it loads at the top, then scrolls down to cell 25. Not my desired result.

I just want to be able to do 2 things here. 1 - Save the cell tapped as a variable. 2 - use scrollToItemAtIndexPath (with the variable in #1) so the view just loads up instantly with the last cell tapped right into the middle, No animations or anything.

Let me know if further clarification is needed. THANKS!

Upvotes: 0

Views: 2563

Answers (1)

kye
kye

Reputation: 2246

You could save the selected indexPathreceived when the collectionview cell is tapped and use it when required.

var selectedIndexPath: NSIndexPath?

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    selectedIndexPath = indexPath
}

func scrollToCell(){

      if let index = selectedIndexPath{
 customViewCollectionView.scrollToItemAtIndexPath(index, atScrollPosition: .CenteredVertically, animated: false)
    }else{
        print("A cell hasnt been selected yet") 
  }
}

Upvotes: 0

Related Questions