Am having a table view with self sizing behaviour, everything runs well on the initial load. Each cell has a provision to add comments which gets displayed on cell under title, and to accomodate the comment text the cell needs to resize itself. I tried to tweak the constraints and called setNeedsLayout on contentView but it doesnt seems to be helping much and the cell doesnt resize. How do I make the cell to resize without reloading the tableview.
Asked
Active
Viewed 289 times
1
-
basically it's what beyowulf said - you need to notify tableView to redraw itself - see https://stackoverflow.com/a/47963680/2912282 for explanation and example and leave an upvote if it helps.. – Milan Nosáľ Jan 23 '18 at 20:18
1 Answers
2
Changes to table view cell dimensions need to be communicated to their parent table view so other cell sizes can be changed. The easiest way of doing this is wrapping size changes in beginUpdates()
and endUpdates()
which will also causes changes to be animated.
For example, suppose I have a UITableViewCell
that has an expanded and collapsed state:
final class TableViewCell: UITableViewCell {
var isExpanded: Bool = false {
didSet {
heightConstraint.constant = isExpanded ? 150 : 75
}
}
lazy var heightConstraint = self.heightAnchor.constraint(equalToConstant: 75)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
heightConstraint.isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
which is controlled by isExpanded: Bool
.
I can expand or collapse all of the visible TableViewCell
s in my table view by saying:
@objc
private func toggleExpanded() {
tableView.beginUpdates()
// Finding all of the visible cells of type `TableViewCell` and changing isExpanded to not isExpanded
tableView.visibleCells.flatMap { $0 as? TableViewCell }.forEach { $0.isExpanded = !$0.isExpanded }
tableView.endUpdates()
// toggle back in 2 seconds
perform(#selector(self.toggleExpanded), with: nil, afterDelay: 2.0)
}
Which results in something like this:
You can see full playground source code here.

beyowulf
- 15,101
- 2
- 34
- 40