Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic row heights of a UITableView inside a UITableViewCell

I have a 'master' UITableView, in which I use different cells that are loaded from .xib's. Some of these cells themselves also have a UITableView.

For now I have set the row height of each cell to the original xib size. However, I would like to have the height dynamic and corresponding to the amount of rows in the 'child' UITableView.

I run into the following problem:

  • Upon ViewController load, the master UITableView needs to have a height for every cell it has.
  • By the time this height is needed, the child UITableView hasn't loaded its own cells yet, and therefore is not the proper size yet.

I have tried the following:

  • At first, load the cell's with a 'estimated' height
  • The cell loads its own tableView and calls to refresh the master tableView

However, in this case, the cell will use the 'estimated' height to lay out its own rows. Therefore it is always too big or too small.

How do I solve this problem?

like image 320
knart Avatar asked Dec 19 '22 01:12

knart


2 Answers

First Approach:

  1. Create a subclass for child tableView and override intrinsicContentSize.

         class MyOwnTableView: UITableView {
        override var intrinsicContentSize: CGSize {
            self.layoutIfNeeded()
            return self.contentSize
        }
    
        override var contentSize: CGSize {
            didSet{
                self.invalidateIntrinsicContentSize()
            }
        }
    
        override func reloadData() {
            super.reloadData()
            self.invalidateIntrinsicContentSize()
        }
    }
    
  2. In Interface builder change the class of your child tableView to MyOwnTableView (subclass UITableView).

  3. Set automatic row height for both the parent and child table view.

        tableView.estimatedRowHeight = 60.0;
        tableView.rowHeight = UITableViewAutomaticDimension;
    

Second Approach: 1. Create a height constraint with any value for child tableView and conect an IBOutlet that sets the child tableView height. 2. Set the height constraint's constant to tableView.contentSize.height

    self.tableViewHeight.constant = self.tableView.contentSize.height
like image 198
Learner Avatar answered Jun 02 '23 13:06

Learner


You could create the object which will create template object of class you want to put in cell, put data in it, calculate its size and return it on sizeForItem method of master tableView. That way you will be able to set returned calculated size for item when master tableView is preparing data.
This is the way i do it in my projects.
You could improve this object with cache, make it generic and use everywhere you may need to.

like image 20
Sergey Fedorov Avatar answered Jun 02 '23 13:06

Sergey Fedorov