Focus above all other views

I have a collection view with image cells that would like to have together without any space. The idea was to have the focused item float over all other cells.


I've implemented the code below, yet when a cell is focused, it doesn't necessarily float above all other cells. It's a really weird effect where other cells sometimes are still above the focused item.


#pragma mark - Focus Engine
- (NSIndexPath *)indexPathForPreferredFocusedViewInCollectionView:(UICollectionView *)collectionView {
    return [NSIndexPath indexPathForItem:0 inSection:0];
}
- (BOOL)collectionView:(UICollectionView *)collectionView canFocusItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldUpdateFocusInContext:(UICollectionViewFocusUpdateContext *)context {
    return YES;
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *indexPaths = [collectionView indexPathsForSelectedItems];
    NSIndexPath *selectedIndexPath = indexPaths.firstObject;
    if (selectedIndexPath) {
        [collectionView deselectItemAtIndexPath:selectedIndexPath animated:YES];
        return NO;
    }
    else {
        return YES;
    }
}


On the storyboard, each cell is a subclass of UICollectionViewCell and each has an image view occupying the cell's entire content area. The following options are set up as follows in the storyboard's image views:


*Adjusts image when focused = ON

*Clip Subviews = OFF


So is it possible to force the focused item to float over all other views?

Accepted Reply

When the cell becomes focused, you can ask it to move in front of its siblings using the UIView method bringSubviewToFront:


[collectionView bringSubviewToFront:focusedCell]

Replies

You might need a custom layout, specifying the desired zIndex in the item's layout attributes. Here's a link with a little bit of discussion (and lots of keywords to search on). stackoverflow.com/questions/31697578/uicollectionview-not-obeying-zindex-of-uicollectionviewlayoutattributes

When the cell becomes focused, you can ask it to move in front of its siblings using the UIView method bringSubviewToFront:


[collectionView bringSubviewToFront:focusedCell]

This is the simplest answer, thank you.

That seems kind of hacky, sidestepping the whole collection view layout mechanism and directly modifying its view hierarchy? I'm surprised if such an approach is "officially" endorsed.

This doesn't appear to work reliably anymore.