How to render a whole UITableView as an UIImage in iOS?

后端 未结 13 2142
太阳男子
太阳男子 2020-12-17 23:54

I have simple UITableView with some data. The table\'s height is greater than the screen size. Now I need to catch screenshot of this table (a whole table). I k

相关标签:
13条回答
  • 2020-12-18 00:38

    Swift 3 version of Young Hoo Kim's answer works for me:

    func generateTableViewImage(_ tableView: UITableView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(tableView.contentSize, false, UIScreen.main.scale)
    
        for section in 0..<tableView.numberOfSections {
            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
    }
    

    It should be noted that if your UITableView is particularly long you may not be able to capture it with the function above as it may require too large an image.

    0 讨论(0)
提交回复
热议问题