An interesting solution to UITableView Layout from Bottom

Phan Viết Trung
Dwarves Foundation
Published in
2 min readJul 10, 2018

Here we have a design of a tableview that adds cells from bottom up.

After researching on StackOverflow https://stackoverflow.com/questions/28105905/how-to-populate-uitableview-from-the-bottom-upwards
I’ve found out that there are mainly 2 solutions:

1- Flip the UITableView flip cells, then reverse order of each cell in the UITableView.

Problem:

  • ScrollViewIndicator is rotated to the left.
  • The Swipe-to-delete action will cause confusion.

2 — Calculate total height of all cells, section headers, and section footers, then set UIEdgeInsetTop to push them down.

Problem:

  • This solution is complicating, and hard to work with Autolayout/UITableViewAutomaticDimension.

I have come up with a solution that fix these problems:

  • As you know, setting multiple UILabel with Autolayout can automatically adjust the content size based on font size, number of characters, etc.

The same solution can be applied to this case:

  • First, use this to calculate the instrinsic layout based on the content size:
class IntrinsicTableView: UITableView {  override var contentSize:CGSize {  didSet {   self.invalidateIntrinsicContentSize()  }}override var intrinsicContentSize: CGSize {  self.layoutIfNeeded()  return CGSize(width: UIViewNoIntrinsicMetric, height:    contentSize.height) }}
  • Set layout for left right bottom of UITableView
  • Set top layout >= 0 so that view can be floated from top to bottom without overflowing the parent view
tableView.snp.makeConstraints { (m) inm.left.bottom.right.equalToSuperview()m.top.greaterThanOrEqualToSuperview()}

Result:
UITableView Layout from Bottom.
Easy to apply everywhere by setting base TableView or just coping few lines of code.

With this solution, there is no need to calculate the height of headers, footers, cells, and at the same time keep Swipe on the TableViewCell working properly.

--

--