Search code examples
swiftuicollectionviewtvos

Taking a snapshot of a UICollectionViewCell


I am making a tvOS app and I want it to look similarly to the Movies app. Therefore I have a UICollectionView. Now my cells are not just simple UIImageViews, but are rather somewhat more complicated.

I still want to have the nice focus visual effect (making the cell image bigger and having the light effect on it when the user swipes the remote). So what I am trying to do is render my cell, then take a snapshot of it and then show this snapshot instead of the cell itself. This is how I do it:

extension UIView {
    var snapshot : UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

...

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = NSBundle.mainBundle().loadNibNamed("ContentCell", owner: self, options: nil)[0] as! ContentCell
    cell.update()
    let cellSnapshot = cell.snapshot

    let snapshotCell = collectionView.dequeueReusableCellWithReuseIdentifier("SnapshotCell", forIndexPath: indexPath) as! SnapshotCell
    snapshotCell.snapshotImageView.image = cellSnapshot
    return snapshotCell
}

However, all this does is show a black cell. Any ideas what might I be doing wrong?


Solution

  • You should look here

    In Swift it will be smth like that:

    extension UIView {
        var snapshot : UIImage? {
            var image: UIImage? = nil
            UIGraphicsBeginImageContext(bounds.size)
            if let context = UIGraphicsGetCurrentContext() {
                self.layer.renderInContext(context)
                image = UIGraphicsGetImageFromCurrentImageContext()
            }
            UIGraphicsEndImageContext()
            return image
        }
    }