单元格内 UIImageView 的子视图的 tvOS 视差效果

tvOS parallax effect for subviews of UIImageView inside cell

我有一个带有 UICollectionView 的 tvOS 应用程序。在每个单元格内有一个 UIImageView,其中 adjustsImageWhenAncestorFocused 设置为 true,当单元格聚焦时,这给了我很好的视差效果。

我正在尝试在该图像的顶部添加一个横幅并将其设置为 "stick",这样视差也会应用到它上面。

我试过将它添加为子视图,将其添加为子层,搞乱了约束,但没有任何效果。每当单元格聚焦时,图像就会产生效果,横幅保持静止。

目前还没有办法将它添加到 UIImageView 中同时获得 Apple 的视差效果。

因此您必须以编程方式实现效果,或者使用 CGContext 绘制图像并在其上绘制横幅。

我正在做后者以在 collectionViewCell 中获得圆形图像,同时还保留 Apple 自己的视差效果。这有点像这样:

imageView.sd_setImage(with: URL(string:url), placeholderImage: UIImage(named: "placeholder"), options: SDWebImageOptions.avoidAutoSetImage) { [weak self] (image, error, cacheType, url) in
    if let image = image {
        if let strongself = self {
            UIGraphicsBeginImageContext(strongself.imageView.frame.size)
            if let ctx = UIGraphicsGetCurrentContext() {
                let layer = CALayer()
                layer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: strongself.imageView.frame.size)
                layer.cornerRadius = 8
                layer.masksToBounds = true
                layer.contentsGravity = "resizeAspectFill"
                layer.contents = image.cgImage
                layer.render(in: ctx)
                let processedImage = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                strongself.imageView.image = processedImage
            }
        }
    }
}

确保在需要时将内容移至后台线程,并且在加载图像时可能已重复使用单元格。因此,在 loadImage 完成处理程序中添加一个检查以获取唯一 ID。