How to get a snapshot of UITableView in a PDF format

前端 未结 5 476
一向
一向 2021-01-31 12:22

I have a UITableView which is populated with some data but since it contains data that is more cells than the viewable area of the screen, I only managed to get onl

5条回答
  •  一整个雨季
    2021-01-31 13:09

    I think everyone forgets that UITableView is a UIScrollView after all. There is no need to calculate cells, height etc. You can simply create your context with the contentSize, set tableView.frame.size = tableView.contentSize and render in context.

    Please see this example

            UIGraphicsBeginImageContext(tableView.contentSize)
            let context = UIGraphicsGetCurrentContext()
    
            let cachedOffset = CGPoint(x:tableView.contentOffset.x , y:tableView.contentOffset.y)
            let cachedFrame = tableView.frame
    
            tableView.contentOffset = .zero
            tableView.frame = CGRect(x: 0, y: 0, width: tableView.contentSize.width, height: tableView.contentSize.height)
            tableView.layer.render(in: context)
    
            tableView.frame = cachedFrame
            tableView.contentOffset = cachedOffset
    
            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                let imageView = UIImageView(image: image)
                self.createPDF(fromUIViews:myImage saveToDocumentsWithFileName:"PDF Name")
            }
    
            UIGraphicsEndImageContext()
    

提交回复
热议问题