tvOS UICollectionView get currently focused item's index path

xinatanil picture xinatanil · Sep 26, 2015 · Viewed 9.2k times · Source

So this is kind of a noobish question but I just can't figure out a very simple way to detect currently focused item's indexPath.
I looked around hoping to see something very easy like collectionView.indexPathOfCurrentlyFocusedItem but didn't find anything remotely close. So I digged around and tried to find something similar at UIFocusEnvironment, UIFocusUpdateContext trying to find the desired property but failed. So, the only solution I can come up with is just iterating through all visible cells and finding a cell with focused property set to true.

So is there a more simple and elegant way to find the currently focused item's indexPath? (Except tracking it through delegate method and saving it in view controller's property)

Answer

Antoine picture Antoine · Sep 30, 2015

You can use UIScreen property focusedView as followed for this:

if let focusedCell = UIScreen.main.focusedView as? UICollectionViewCell {
    if let indexPath = collectionView.indexPath(for: focusedCell) {
        print("IndexPath is \(indexPath)")
    }
}