swift - 拍摄 UICollectionViewCell 的快照

标签 swift uicollectionview tvos

我正在制作一个 tvOS 应用程序,我希望它看起来与电影应用程序类似。因此我有一个 UICollectionView。现在我的单元格不仅仅是简单的 UIImageView,而是更加复杂。

我仍然希望拥有漂亮的焦点视觉效果(使单元格图像更大,并在用户滑动 Remote 时在其上产生灯光效果)。所以我想做的是渲染我的单元格,然后拍摄它的快照,然后显示该快照而不是单元格本身。我就是这样做的:

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
}

但是,这只是显示一个黑色单元格。有什么想法我可能做错了什么吗?

最佳答案

你应该看看here

在 Swift 中,它会是这样的:

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
    }
}

关于swift - 拍摄 UICollectionViewCell 的快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33388116/

相关文章:

ios-Xcode 10 : Razorpay pod "module compiled with Swift 4.1 cannot be imported by the Swift 4.2 compiler"

swift - UIScrollView滚动条的宽度和高度?

ios - 选择单元格时如何自动滚动collectionviewcell到最近的单元格(上一个或下一个)

swift - 我们可以使用 UIButton 停止或删除焦点上的动画效果并提供其他边框效果 tvOS

xcode - TVOS 自动化

swift - 如何使用 Apple TV 上的焦点引擎使 UIImageView 可聚焦

ios - 如何在 Swift 中将 func 中的值设为全局常量

ios - Swift 3 - SQLite 包装器

xcode - Swift:单元格或标签是 UIcollectionView 中的 http 链接

ios - UICollectionView 滚动错误