Re: Cannot move focus off of UIButton in UICollectionViewCell

I have a UICollectionView of custom UICollectionViewCell subclasses, each with a UILabel and a UIButton. I want to make use of the great default focus behavior of the UIButton (since UICollectionViewCells don't have any default focus behavior), so I override the preferredFocusedView property of the UICollectionViewCell subclass to return the UIButton:

When I do this, I'm unable to move the selection to the next UICollectionViewCell. The context object of collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:) reports that the previous and next NSIndexPaths are always (0,0).

If I instead return self or self.textLabel from preferredFocusView and do custom focus appearance changes (like changing the backgroundColor of the UICollectionViewCell), I'm able to move focus around the UICollectionView without problem. collectionView(_:canFocusItemAtIndexPath:) has not been overridden. Is there some default behavior of focus in the UIButton that I'm overlooking?

If preferredFocusedView is not overridden to return the UIButton, the focus moves around the UICollectionView as expected, but the UIButton in the UICollectionViewCell does not receive focus (does not get the white background with shadow), as evidenced by firings of collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:). The focused property of the UIButton when moving through the UICollectionView (from nextFocusedIndexPath) in that delegate method remains false.

Without overriding preferredFocusView in TestCollectionViewCell, you can move around the UICollectionView fine, but the UIButton (the only view in the cell) never gets focus. If you return the button from preferredFocusedView, the button gets focus, but only in (0,0).

This works! This also makes no sense on immediate inspection: the cell cannot obtain focus, but one of its child views can? This lead me to discover something else. UICollectionView has a property, remembersLastFocusedIndexPath, that I set to true. If this is false, I do not need to implement canFocusItemAtIndexPath. Reading the documentation a little more thoroughly, I think I see what may have been happening. A reading of the documentation for this property along with mwhuss's initial reply may reveal that this isn't a bug, but perhaps really strange default behavior (in my opinion).

More Like This

Retrieving data ...

This site contains user submitted content, comments and opinions and is for informational purposes only. Apple disclaims any and all liability for the acts, omissions and conduct of any third parties in connection with or related to your use of the site. All postings and use of the content on this site are subject to the Apple Developer Forums Participation Agreement.