Daniel
Daniel

Reputation: 693

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.

Upvotes: 5

Views: 3816

Answers (2)

tmm1
tmm1

Reputation: 2115

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

Upvotes: 1

Breek
Breek

Reputation: 1441

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

Upvotes: 3

Related Questions