0

I have UITableView with 2 cells that do AutoLayout (quite simple, UILabel and UISwitch, and UILabel and UIImageView). I want to get tableView heihgt. UITableView reside to UIView, so i did following:

 override func layoutSubviews() {
    super.layoutSubviews()
    if !isLayoutSubviewsDone {
      expectedHeight = tableView.contentSize.height
      isLayoutSubviewsDone = true
      didLayoutSubivews?()
    }
  }

unfortunately, tableView.contentSize.height is smaller that it should be. for about 20%. How to get exact height amount?

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

2 Answers2

1

How to get exact height amount?

There is no magic way to size a table to its contents. The table view has no automatic size. It is not magically sized by the heights of its cells. You have to work out the height of every cell yourself, one at a time, and add them up.

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

If you add observer to TableView, I'm sure you will get exact table view height. Try below code.

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        expectedHeight.constant = tableView.contentSize.height
    }

//MARK:- Add Observer on Reload tableView

   tableView.addObserver(self, forKeyPath: "tableViewObserver", options: [], context: nil)
   tableView.reloadData()
Abdul Hoque Nuri
  • 1,105
  • 1
  • 9
  • 18