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..
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
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
}
}
}
Most of your approach is right, add this below steps too. If you already done any step put as check mark.
numberOfLines
property to zeroImplement these two tableView delegates methods
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat{
return 55
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return UITableViewAutomaticDimension
}
Now run your project and check.
Expected output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With