uitableview content size is not returning correctly swift

siva krishna picture siva krishna · Mar 9, 2017 · Viewed 7.7k times · Source

I'm using uitableview in container view, so want to set my container height based on content size height. So after reloading tableview i'm changing height of container.but it seems it is calculating based on estimated height. it's not giving actual height.

This is my constraints layout.

Thank you..enter image description here

    instructiontableview.estimatedRowHeight = 55

    instructiontableview.rowHeight = UITableViewAutomaticDimension

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension

  }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // assigning multiline text to my label 


        cell.layoutIfNeeded()
        cell.sizeToFit()
        return cell
    }
    return UITableViewCell()
}

Now I'm reloading from my container view controller and chnanging height

Answer

siva krishna picture siva krishna · Mar 14, 2017

I tried reloadData() and layoutIfNeeded() and tried many different ways. nothing has worked for me. Finally I solved it by using KVO.

Here is my code

override  func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.instructiontableview.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

}
override func viewWillDisappear(_ animated: Bool) {
    self.instructiontableview.removeObserver(self, forKeyPath: "contentSize")
    super.viewWillDisappear(true)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?){
    if(keyPath == "contentSize"){

        if let newvalue = change?[.newKey]{
            let newsize  = newvalue as! CGSize
            self.heightofinstructioncontainerview.constant = newsize.height
        }
    }
}