0

I have a UITableView(Table 1). Inside UITableView Cell I have an another UITableView(Table 2).

In Table 2 the rows's height is UITableViewAutomaticDimension.

My requirement is - I want that Table 2 should not be scroll and takes its full height as per number of rows inside it.So, As per this Table 2 's height I need to set Table 1's row height.

I am using Table 2 's contentSize.height, but its not working. I searched a lot but found nothing.

Code :

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
         let cell = tableView_First.dequeueReusableCell(withIdentifier: "SecondTableViewCell") as!  SecondTableViewCell

        return cell.second_TableView.contentSize.height
    }

Update:

I have debugged the code and found Table 2's cell's estimated height effects the height of Table 1's cell. i.e- If estimated height of Table 2's cell is 100 and these are 5 cells. Then this cell.second_TableView.contentSize.height gives me 500. Which is wrong.Because cell has different height 10, 20, 30, 40, 10.

Any suggestions will be appreciated.

Thanks!

Amanpreet
  • 1,301
  • 3
  • 12
  • 29

2 Answers2

0

May you are getting the wrong result because of below two reasons

  1. When you are getting cell.second_TableView.contentSize.height that time your cell.second_TableView might not be loaded completely thus you are getting wrong height.

  2. You are dequeuing new cell rather getting existing loaded cell.

Please try below code:

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

//Get existing cell rather deque new one
         let cell = tableView_First.cellForRowAtIndexPath(indexPath) as!  SecondTableViewCell

//This will force table view to load completely 
   cell.second_TableView.layoutIfNeeded()

        return cell.second_TableView.contentSize.height
    }

Hope this will solve your problem.

Govind Prajapati
  • 957
  • 7
  • 24
  • Thanks for answer. But this new piece of code gives me "Bad _Access". I checked the error https://stackoverflow.com/questions/35931478/why-tableview-cellforrowatindexpathindexpath-give-me-a-bad-access-error. Can you suggest what to do now? – Amanpreet Jun 13 '17 at 05:18
0

write this two lines in viewDidLoad,

tableView.estimatedRowHeight = 241

tableView.rowHeight = UITableViewAutomaticDimension

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

sumeet
  • 157
  • 1
  • 5