Search code examples
swiftuitableviewuigraphicscontextuitableviewautomaticdimension

How to Iterate through all UITableView sections?


I'm trying to convert a UITableView with multiple section and dynamic rows.

I'm currently trying to loop through all the subviews of a UITableView. I'm trying to insert each subview into a container UIView where I could combine them all to make up a UIView representing one page for a specific height limit, where I may add a footer dynamically.

Basically the goal is to iterate through all sections, and combine all view for each cell into one big UIView that represents that section including the section header.

This is so I could easily just convert each UIView into specific PDF pages later on. As if I just directly convert the UITableView into PDF, I would get page cuts where I don't want them.


Solution

  • I was able to iterate through all UITableView sections and row through code below:

    The logic here is that to be able to get the right subview that I've appended to the cell.contentView, I've set them with a tag before adding them as Subview, so that I would be able to get the exact view that I've added instead of the wrapping contentView.

    var subviews = [UIView]()
    let sectionCount = tableView.numberOfSections
    
    /// loop through available sections
    for section in 0..<sectionCount {
    
        /// get each section headers
        if let sectionHeader = self.tableView(tableView, viewForHeaderInSection: section) {
            subviews.append(sectionHeader)
        }
    
    
        if tableView.numberOfRows(inSection: section) > 0 {
            /// loop through rows within section
            for row in 0..<tableView.numberOfRows(inSection: section) {
                let indexPath = IndexPath(row: row, section: section)
                tableView.scrollToRow(at: indexPath, at: .top, animated: false)
                if let currentCell = tableView.cellForRow(at: indexPath), let view = currentCell.contentView.viewWithTag(999) {
                    subviews.append(view)
                }
            }
        }
    }