Swift - how to add a layer to a UIImageView inside a UICollectionViewCell and save the parallax effect

I am working on a tvOS project. This project contains UICollectionViewwith UIImageViewinside each UICollectionViewCell. First of all, I use adjustsImageWhenAncestorFocusedon the image, because it looks good when the cell is in focus, and I want to have the parallax effect.

When the cell is in focus, an inscription should appear (for the product name), which is not a problem to create. But I want the title to be well readable, so I want to lay a gradient layer on top of the image.

Problem: When I add a gradient layer to the UIImageView, it comes out on top of it, but it does not “stick” to it. It should go with the image when the user does the parallax operation, but it remains in its position, and the original image moves under the gradient layer.

Problem screenshot Actual problem

The code

let gradientLayer = CAGradientLayer()

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {

    gradientLayer.colors = [UIColor(red:0.00, green:1.00, blue:1.00, alpha:0.3).cgColor, UIColor(red:1.00, green:0, blue:1.00, alpha:0.3).cgColor]
    gradientLayer.frame = productImageView.focusedFrameGuide.layoutFrame
    gradientLayer.isHidden = true
    self.productImageView.layer.addSublayer(self.gradientLayer)

    if (self.isFocused){
        gradientLayer.isHidden = false
    }
    else {
        gradientLayer.isHidden = true
    }

}

Additional question

This is mistake? Because I still do not understand how to solve this problem. Should I give it to Apple?

+4
source share
1 answer

Apple introduced overlayContentViewin tvOS 11. You have to add your shortcut to this view and it will do the trick for you!

https://developer.apple.com/documentation/uikit/uiimageview/2882128-overlaycontentview?changes=latest_minor

+3

Source: https://habr.com/ru/post/1667772/


All Articles