简体   繁体   中英

TableView Cell Dynamic Height

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. ie- 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!

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.

write this two lines in viewDidLoad,

tableView.estimatedRowHeight = 241

tableView.rowHeight = UITableViewAutomaticDimension

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM