Home > Software design >  Dynamic height of tableview cell on basis of UICollectionView cell inside it
Dynamic height of tableview cell on basis of UICollectionView cell inside it

Time:10-05

I have tableview cell inside which i have collectionview and further it has collectionview cell, how can i set height of tableview on basis of collectionview cell ?

CodePudding user response:

Try to add this in your controller

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

CodePudding user response:

Your question is vague.

You suppose to provide an example of what you're trying to achieve.

Suppose you have static height for collection view cell: Easy, auto layout will be your friend. Using:

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

However, if you would like to dynamically layout table view cell height:

  1. Set height constraint for minimum height of collection view cell
  2. Calculate the content size:

// You may need to call it when viewDidLayoutSubviews() is called
let height = collectionView.collectionViewLayout.collectionViewContentSize.height
collectionViewHeightConstraint.constant = height
contentView.layoutIfNeeded()
  • Related