Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection view's last focused index path lost after reload data in tvOS

In my tvOS app, I have a collection view where I've set its remembersLastFocusedIndexPath to true. As this is not enough to get this behaviour, I've also overridden a method in my UIViewController like this:

override weak var preferredFocusedView: UIView? {
    return collectionView
}

This was working fine until I started reloading the collection view for some reasons. It does work if, being the collection view visible, I call collectionView.reloadData().

This doesn't work, tho, if I do the reload when the collection view is not visible, for example, when I'm in a detail view after tapping one of the items. When I come back to the grid, the focused index path is not the one I tapped.

As a workaround, I'm managing this non-ideal scenario:

  1. As the reload is triggered by fresh data coming from my backend, I only call collectionView.reloadData() when the collection view is visible (because I know that the last focused index doesn't change here).
  2. I call collectionView.reloadData() in viewDidAppear(animated: Bool) to have the latest content available when the user comes back.

How can I do this properly? Thanks in advance.

like image 803
Daniel Avatar asked Sep 26 '22 13:09

Daniel


2 Answers

Recently I got this issue also, my situation is pretty much same to you.

I also called collectionView.reloadData() in viewDidLoad and viewWillAppear

And then

I changed from

collectionView.reloadData()

to

collectionView.reloadItemsAtIndexPaths(collectionView.indexPathsForVisibleItems())

It works for me most of time, there is still approximately <5% chance to mess up the last focus index

like image 195
Breek Avatar answered Oct 11 '22 05:10

Breek


One option is to set remembersLastFocusedIndexPath to false, and implement indexPathForPreferredFocusedViewInCollectionView: to achieve the same behavior.

like image 27
tmm1 Avatar answered Oct 11 '22 05:10

tmm1