Dave G Dave G - 5 months ago 75
Swift Question

Capture UITableView as Image - With Scrolling

My Swift code for capturing a UITableView as an image isn't working when the table is scrolled down. I essentially have the answer in Objective-C but can't seem to make it work in Swift. Currently this is what I have in Swift:

func snapshotOfCell (inputView: UIView) -> UIView {
UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
let cellSnapshot : UIView = UIImageView(image: image)
cellSnapshot.layer.masksToBounds = false

return cellSnapshot

I found this answer but it's in Objective-C:

-(UIImage *) imageWithTableView:(UITableView *)tableView {
UIView *renderedView = tableView;
CGPoint tableContentOffset = tableView.contentOffset;
UIGraphicsBeginImageContextWithOptions(renderedView.bounds.size, renderedView.opaque, 0.0);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(contextRef, 0, -tableContentOffset.y);
[tableView.layer renderInContext:contextRef];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
return image;

It seems to fix the scroll problem by using a contentOffset. However, I've been trying to integrate it into my Swift function without success. Anyone good with both Objective-C and Swift? Thanks!


capture whole tableview as a image

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(tableView.contentSize.width, tableView.contentSize.height),false, 0.0)

    let context = UIGraphicsGetCurrentContext()

    let previousFrame = tableView.frame

    tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.contentSize.width, tableView.contentSize.height);


    tableView.frame = previousFrame

    let image = UIGraphicsGetImageFromCurrentImageContext()

    imageView.image = image;

capture the screenshot of tableview in a scrolled position

    let contentOffset = tableView.contentOffset

    UIGraphicsBeginImageContextWithOptions(tableView.bounds.size, true, 1)

    let context = UIGraphicsGetCurrentContext()

    CGContextTranslateCTM(context, 0, -contentOffset.y)


    let image = UIGraphicsGetImageFromCurrentImageContext()

    imageView.image = image;