I want to get snapshot for cell after long press and I get it working. I am creating snapshots by this code:
func customSnapShotFrom(view:UIView) -> UIView { // calling this with UITableViewCell input
let snapshot:UIView = view.snapshotViewAfterScreenUpdates(false) // here I tried true and false
snapshot.layer.masksToBounds = false
snapshot.layer.cornerRadius = 0.0
snapshot.layer.shadowOffset = CGSizeMake(2.0, 2.0)
snapshot.layer.shadowOpacity = 1.0
return snapshot
}
It's working but sometimes I get this message in output:
Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.
I get it only for some of the cells (just few) and not always. Sometimes it generates snapshot from that cell other time it returns nil. I've checked and I have always cell in input. So why is that? Why rendering results in an empty snapshot? Thanks
Edit: I have added gesture recognizer to my tableView:
let longPress = UILongPressGestureRecognizer(target: self, action: "longPressDetected:")
self.tableView.addGestureRecognizer(longPress)
And I am creating snapshot in longPressDetected
method:
func longPressDetected(sender: AnyObject) {
...
switch (state) {
case UIGestureRecognizerState.Began :
...
let cell:UITableViewCell = self.tableView.cellForRowAtIndexPath(indexPath)!
snapshot = self.customSnapShotFrom(cell)
...
My swift solution thanks to kirander answer:
func customSnapShotFrom(view:UIView) -> UIView {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let cellImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageView = UIImageView(image: cellImage)
imageView.layer.masksToBounds = false
imageView.layer.cornerRadius = 0.0
imageView.layer.shadowOffset = CGSizeMake(2.0, 2.0)
imageView.layer.shadowRadius = 4.0
imageView.layer.shadowOpacity = 1.0
return imageView
}