Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uitableview content size is not returning correctly swift

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

like image 320
siva krishna Avatar asked Mar 09 '17 10:03

siva krishna


Video Answer


2 Answers

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
        }
    }
} 
like image 72
siva krishna Avatar answered Mar 03 '23 11:03

siva krishna


Most of your approach is right, add this below steps too. If you already done any step put as check mark.

  1. Change label numberOfLines property to zero

enter image description here

  1. add constraints to label

enter image description here

  1. Change height constraint relationship

enter image description here

  1. Implement 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:

enter image description here

like image 26
dahiya_boy Avatar answered Mar 03 '23 10:03

dahiya_boy