UITableView with dynamic height with auto layout constraints

This question already has an answer here:


ANSWERS:


So I guess you have a MasterViewController which has a tableView in it. Then you want to add another tableView which is part of the class MyCustomcell, inside one of the cell of MasterViewController's tableView.

Adding customCell with tableView is not a big deal, but calculating and maintaining the height of MasterViewController in accordance with the data to be shown in CustomCell is a bit tricky. If you are asking just about how to add CustomCell in a tableView then there are many good tutorials available which you can easily get just by a quick google.

I faced a similar situation and solved the problem in following way. Hope this helps.

1) If you have a customCell where you just have to show texts. Then the height of tableView of MasterViewController can easily be maintained automatically with auto layout depending on the content of texts. This tutorial has a very good explanation.

2) If you are adding tableView inside one of the cell of MasterViewcontroller tableView then it becomes tricky. Now the height of the cell of MasterViewController depends on the content of height of the CustomCell tableview height. I tried to handle this situation by applying different ways in Swift 3 but finally got the result by following this way:-

class MasterViewController: UIViewController {
          @IBOutlet weak var tableView: UITableView!

          var customCell:MyCustomCell? = nil

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! MyCustomCell
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        customCell = cell
        return cell
    }

}

extension MasterViewController:UITableViewDelegate{

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

         if let aHeight = customCell?.tableView.contentSize.height{
             return aHeight
         }

         return 0

     }

}


 MORE:


 ? Dynamic UITableView Cell Height Based on Contents
 ? Change UITableView height dynamically iOS7
 ? Autolayout - Vertically center two views in a UITableViewCell when one view has dynamic height
 ? UITableViewCell in nib or storyboard
 ? Change Height of UITableView Customcell
 ? Auto resize a cell in tableview based on dynamic input
 ? IOS:Multiple PrototypeCells in UITableView
 ? Dynamic cell height for tableview
 ? UITableViewCell of different heights
 ? UITableViewCell, UITextView with dynamic height