Home > Back-end >  UITableView to UIImage Swift
UITableView to UIImage Swift

Time:02-01

I am converting UITableView to UIImage with following method:-

func generateTableViewImage(_ tableView: UITableView) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(tableView.contentSize, false, UIScreen.main.scale)

    for section in 0..<tableView.numberOfSections {
        guard let headerCell = tableView.headerView(forSection: 0) else { continue }
        headerCell.contentView.drawHierarchy(in: headerCell.frame, afterScreenUpdates: true)
        for row in 0..<tableView.numberOfRows(inSection: section) {
            let indexPath = IndexPath(row: row, section: section)
            guard let cell = tableView.cellForRow(at: indexPath) else { continue }
            cell.contentView.drawHierarchy(in: cell.frame, afterScreenUpdates: true)
        }
    }
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

Ref link:- How to render a whole UITableView as an UIImage in iOS?

But it converting only cells to image, I need to get the whole table including header and footer views.

I tried with below code:-

guard let headerCell = tableView.headerView(forSection: 0) else { continue }
            headerCell.contentView.drawHierarchy(in: headerCell.frame, afterScreenUpdates: true)

headerCell returning the actual header but not showing on image.

Question:- Can someone please explain to me how to show the table view as image including header and footer as well, I've tried with above code but no results yet.

Can someone please explain to me How to get Progress?

Any help would be greatly appreciated.

Thanks in advance.

CodePudding user response:

Try this:

func tableToImg(_ tblView : UITableView) -> UIImage {
    UIGraphicsBeginImageContext(tblView.frame.size)
    tblView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}
  •  Tags:  
  • Related