Skip to content

Instantly share code, notes, and snippets.

@phlippieb
Created March 15, 2019 06:57
Show Gist options
  • Save phlippieb/0afb37525e7789a2e59f8e072e5159e3 to your computer and use it in GitHub Desktop.
Save phlippieb/0afb37525e7789a2e59f8e072e5159e3 to your computer and use it in GitHub Desktop.

Revisions

  1. phlippieb created this gist Mar 15, 2019.
    46 changes: 46 additions & 0 deletions ResizingTableViewCellDelegate.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    /*
    This code demonstrates a way to get UITableViewCells to resize
    after their content size has changed, without needing to reload
    the cells.

    Prerequisites:
    - The table view must be set up to calculate its cell heights dynamically; i.e.
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 100 // or some good estimate
    - The cell must be laid out using auto layout. Remember to add the subviews to
    the cell's contentView.
    */



    protocol ResizingTableViewCellDelegate: class {
    func resizeTableViewCells()
    }

    extension UITableView: ResizingTableViewCellDelegate {
    func resizeTableViewCells() {
    self.beginUpdates()
    self.endUpdates()
    }
    }

    // How to use:

    class MyTableViewCell: UITableViewCell {
    // In your tableView(:cellForRowAt:), after the cell
    // is dequeued, do `cell.delegate = tableView`
    weak var delegate: ResizingTableViewCellDelegate

    // Add your subviews and dynamic layout here...

    // Call this when the cell content or size changes.
    private func resize() {
    // Animate the layout change:
    UIView.animateWithDuration(0.3) {
    cell.contentView.layoutIfNeeded()
    }

    // Ask the delegate (i.e. the tableview) to resize the cell:
    self.delegate?.resizeTableViewCells()
    }
    }