Created
September 14, 2021 00:38
-
-
Save chrisvasselli/d8e4e1bf987e6885d02104b1990d4978 to your computer and use it in GitHub Desktop.
Create full page screenshots from a table view controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
extension UITableViewController: UIScreenshotServiceDelegate { | |
public func screenshotService(_ screenshotService: UIScreenshotService, generatePDFRepresentationWithCompletion completionHandler: @escaping (Data?, Int, CGRect) -> Void) { | |
let originalFrame = tableView.frame | |
let originalContentOffset = tableView.contentOffset | |
// Layout into an extra large frame, to force the actual heights to be calculated for all rows with estimated heights | |
let oversizedContentSize = CGSize(width: tableView.contentSize.width, height: 100000) | |
tableView.frame = CGRect(origin: .zero, size: oversizedContentSize) | |
tableView.layoutIfNeeded() | |
let actualContentSize = tableView.contentSize | |
let data = NSMutableData() | |
UIGraphicsBeginPDFContextToData(data, .zero, nil) | |
UIGraphicsBeginPDFPageWithInfo(CGRect(origin: .zero, size: actualContentSize), nil) | |
if let context = UIGraphicsGetCurrentContext() { | |
tableView.contentOffset = .zero | |
tableView.frame = CGRect(origin: .zero, size: actualContentSize) | |
tableView.layoutIfNeeded() | |
tableView.layer.render(in: context) | |
} | |
else { | |
completionHandler(nil, 0, .zero) | |
} | |
UIGraphicsEndPDFContext() | |
tableView.frame = originalFrame | |
tableView.contentOffset = originalContentOffset | |
let offsetInPDF = actualContentSize.height - originalContentOffset.y - originalFrame.height | |
completionHandler(data as Data, 0, CGRect(origin: CGPoint(x: 0, y: offsetInPDF), size: self.view.frame.size)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment