0
votes

I have question how to implement (or is it even possible) to implement dynamic UITableView height with dynamic UITableViewCells. So, I have something like news details that have some views on top (picture, labels etc) and below all of that I want to make comments sections. Comments scrolling is false and I need to resize whole tableview and whole screen to match all content size. I know that tableView is scrollView and that I could make whole news details view like tableview where header would be all views(like images, labels etc).

But Can I make it work like this? I made View -> ScrollView -> View (content view) that have [Images (with fixed height), labels etc. AND comments tableView (that need to have content size height, not scrollable)] I tried with

tableView.isScrollEnabled = false
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 220 

override func viewWillLayoutSubviews() {
super.updateViewConstraints()
self.tableViewHeight?.constant = self.tableView.contentSize.height
 }

But no luck. Only thing that happened is that I get content size calculated by formula rows.count * estimatedRowHeight so sometimes I got some content cut and sometimes I got so much empty space below table. Thank you!

EDIT: Here is solution

class ViewController: UIViewController {

  @IBOutlet weak var tableView: UITableView!
  @IBOutlet weak var tableViewHeight: NSLayoutConstraint!

  private var contentSizeObservation: NSKeyValueObservation?

  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.isScrollEnabled = false
    tableView.dataSource = self
    contentSizeObservation = tableView.observe(\UITableView.contentSize, options: [.new]) { (_, change) in
      if let newSize = change.newValue {
        self.tableViewHeight.constant = newSize.height
      }
    }
  }

}
1

1 Answers

0
votes

I think what you need is only one UITableView. Just add your comments as the cells and setup your news details as tableHeaderView: https://developer.apple.com/documentation/uikit/uitableview/1614904-tableheaderview.

If you want to use AutoLayout inside TableView header you would have to do some workarounds but still fairly easy, you will find a lot of topics about it on StackOverflow. For my case I've created simple extension for UITableView:

internal extension UITableView {

    /// Workaround for not working AutoLayout with UITableView.tableHeaderView
    /// This function needs to be called after calculating TableView position
    /// In case of UIViewController: viewDidLayoutSubviews()
    /// In case of UIView: layoutSubviews()
    func relayoutTableHeaderView() {
        guard let tableHeaderView = tableHeaderView else { return }
        tableHeaderView.layoutIfNeeded()
        tableHeaderView.frame.size = tableHeaderView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
        self.tableHeaderView = tableHeaderView
    }
}

Both header and cells can be calculated dynamically using AutoLayout