我想在长按后获取单元格的快照并让它工作。我正在通过此代码创建快照:
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
}
它正在工作,但有时我会在输出中收到此消息:
对尚未渲染的视图进行快照会导致快照为空。确保在快照或屏幕更新后的快照之前至少渲染一次视图。
我只为某些细胞(只有少数)得到它,而且并非总是如此。有时它会从该单元格生成快照,而有时它会返回 nil。我已经检查过了,我总是输入单元格。那为什么呢?为什么渲染会导致空快照?谢谢
编辑: 我已将手势识别器添加到我的 tableView:
let longPress = UILongPressGestureRecognizer(target: self, action: "longPressDetected:")
self.tableView.addGestureRecognizer(longPress)
我正在longPressDetected
方法中创建快照:
func longPressDetected(sender: AnyObject) {
...
switch (state) {
case UIGestureRecognizerState.Began :
...
let cell:UITableViewCell = self.tableView.cellForRowAtIndexPath(indexPath)!
snapshot = self.customSnapShotFrom(cell)
...
感谢kirander 的回答,我的快速解决方案:
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
}