Created
March 15, 2019 06:57
-
-
Save phlippieb/0afb37525e7789a2e59f8e072e5159e3 to your computer and use it in GitHub Desktop.
Even when using AutoLayout and UITableView.automaticDimension, it's not obvious how to make your table view resize a cell when its content changes without reloading the entire cell. I've had success with calling beginUpdates() and endUpdates() on the table view after the content changes. This gist simply extracts that into a delegate.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment