Search code examples
uiimageviewuicollectionviewcelltvos

How can I change the default animation behavior of a UIImageView when it is focused inside a UICollectionViewCell?


I have a UICollectionViewController and a UIImageView as an IBOutlet inside each cell. I set imageView.adjustsImageWhenAncestorFocused = true for the image views and when the related cell is focused, the image view gets too big. Just wondering if there is any way to control the animation behavior of the image view. I know I can override didUpdateFocusInContext(_:withAnimationCoordinator:), but couldn't find out how to handle hover event.
Any help would be appreciated.


Solution

  • So use didUpdateFocusInContext function to update your cell when focus on current selected cell.

    First disable adjustsImageWhenAncestorFocused property for the image view then change size of imageview as per your wish.

    Define two different sizes and use it for focused cell and rest of the cell.

    CGSize originalCellSize = CGSizeMake(225, 354);
    CGSize focusCellSize = CGSizeMake(240, 380);
    
    - (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
    {
        [coordinator addCoordinatedAnimations:^{
            if (self.focused) {
                self.imageView.frame.size = focusCellSize;
            } else {
                self.imageView.frame.size = originalCellSize;
            }
        } completion:nil];
    }
    

    Use animatewithDuration: to give better animation style when you changing cell size or use alpha or shadow effect for imageview for more perfect look.