Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remembersLastFocusedIndexPath not working on UICollectionView

Tags:

tvos

I have a collection view with a standard horizontal layout. Upon presenting a view controller and then dismissing it, the collection view reset focus back to the first cell, even though the last focused cell was not that one.

I've set

self.collectionView.remembersLastFocusedIndexPath = YES;

What's weird is that this only happens when I push a view controller on my navigation controller.

So if I do

[self.navigationController pushViewController:controller animated:YES];

and then dismiss, remembersLastFocusedIndexPath does not work properly.

However, if I:

[self presentViewController:controller animated:YES completion:nil];

Then it works as expected.

Any idea why it wouldn't work via a navigation controller?

like image 676
Snowman Avatar asked Sep 26 '15 00:09

Snowman


3 Answers

What worked for me was ensuring that preferredFocusView on the viewController was the collection view:

override weak var preferredFocusedView: UIView? {
    return collectionView
}

After this remembersLastFocusedIndexPath seems to work.

like image 118
cfraz89 Avatar answered Oct 12 '22 23:10

cfraz89


make sure that you don't reloadData() on viewWillAppear of your collectionView or TableView. Otherwise rememberedFocus will be reseted to default (for collection view in my case it was the centre visible cell)

like image 40
protspace Avatar answered Oct 13 '22 01:10

protspace


By default, the system remembers the position. You should probably fix this issue by setting remembersLastFocusedIndexPath to false.

You could also implement the UICollectionViewDelegate method: func indexPathForPreferredFocusedViewInCollectionView(collectionView: UICollectionView) -> NSIndexPath?

The documentation tells us:

The functionality of this delegate method is equivalent to overriding the UICollectionView class’s preferredFocusedView method in the UIFocusEnvironment protocol. If the collection view’s remembersLastFocusedIndexPath method is set to YES, this method defines the index path that gets focused when the collection view is focused for the first time.

But for your issue, setting remembersLastFocusedIndexPath to false should fix it.

like image 40
Antoine Avatar answered Oct 13 '22 01:10

Antoine