0

How can I push the user to the photo they selected (selected index), and push them to that photo but still allow them to scroll up or down to the previous or next photo of that selected index?

The issue I am having is, when the viewController is pushed, it takes me to the first index instead of the selected one.

When a photo is tapped, I would like it to push to the selected photo

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let singlePostVC = (storyboard!.instantiateViewController(withIdentifier: "SinglePostVC") as? SinglePostVC)!

    singlePostVC.posts = posts
    singlePostVC.selectedIndex = indexPath.row

    navigationController?.pushViewController(singlePostVC, animated: true)
    self.navigationController?.navigationBar.backIndicatorImage = #imageLiteral(resourceName: "BackButton")
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: UIBarButtonItem.Style.plain, target: nil, action: nil)
    self.navigationItem.backBarButtonItem?.tintColor = UIColor(named: "darkModeLabels")

}

Here is the code for SinglePostVC

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int.   {

    return posts.count


}



func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SinglePostCell", for: indexPath) as! PostsCell

    cell.delegate = self
    cell.post = posts[indexPath.row]

    handleUsernameLabelTapped(forCell: cell)
    handleMentionTapped(forCell: cell)
    handleHashTagTapped(forCell: cell)

    return cell
}



func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}



override func viewDidLoad() {
    super.viewDidLoad()


    let indexPath = IndexPath(item: selectedIndex, section: 0)
    postsCollectionView.scrollToItem(at: indexPath, at:.bottom , animated: true)

}

Parth
  • 2,682
  • 1
  • 20
  • 39
Clint
  • 387
  • 5
  • 25

1 Answers1

1

You should put your line of:

let indexPath = IndexPath(item: selectedIndex, section: 0)
postsCollectionView.scrollToItem(at: indexPath, at:.bottom , animated: true)

inside the viewDidAppear method instead of viewDidLoad like so:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)


    let indexPath = IndexPath(item: selectedIndex, section: 0)
    postsCollectionView.scrollToItem(at: indexPath, at:.bottom , animated: true)

}

What's happening is you're telling it to scroll to this certain indexPath of the CollectionView, but the CollectionView hasn't actually appeared, so once it does it basically overwrites the command you told it to execute and just displays it like normal. When you use viewDidAppear it waits until the view is shown to the user, THEN it displays the scroll.

Pierce
  • 3,148
  • 16
  • 38