0

I am using collectionview inside the tableview cell

here if i return homeData?.result?.category_json?.count ?? 0 with JSON data then collectionview is not changing to dynamic height initially.. if i go down to the tableview and come up then showing dynamically.. why?

i have given collectionview height as 120 in storyboard and i have taken its height outlet in tableview cell class TopCategoryTableCell like

class HomeVC: UIViewController{

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad(){
    self.tableView.reloadData()
 }

extension HomeVC : UITableViewDelegate,UITableViewDataSource{

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == self.tableView {
        switch indexPath.section {
        case 0:
             let cell = tableView.dequeueReusableCell(withIdentifier: "TopCategoryTableCell", for: indexPath) as! TopCategoryTableCell
            cell.selectionStyle = .none
            cell.vc = self
            cell.countItems = homeData?.result?.category_json?.count ?? 0
            cell.collectionView.reloadData()
            return cell
     }
  }


class TopCategoryTableCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource{

@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var topCatcollectioVCHeight: NSLayoutConstraint!
    
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return homeData?.result?.category_json?.count ?? 0// count is 10
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCollectionCell", for: indexPath) as! HeaderCollectionCell

    cell.lblTitle.text = "check"
    self.topCatcollectioVCHeight.constant = collectionView.contentSize.height
    
    return cell
}
}

o/p: here the homeData?.result?.category_json?.count ?? 0 count is 10 .. but not showing collectionview height dynamically.. if i scroll and go down to tableview then i come to top then showing collectionview height dynamically

enter image description here

how to to initially also show collectionview height dynamically please do guide

Swift
  • 1,074
  • 12
  • 46

1 Answers1

1

Subclass Collectionview & override layoutSubviews() like this.

class DynamicHeight: UICollectionView {
  override func layoutSubviews() {
    super.layoutSubviews()
    if!__CGSizeEqualToSize(bounds.size,self.intrinsicContentSize){
      self.invalidateIntrinsicContentSize()
    }
  }
  override var intrinsicContentSize: CGSize {
    return contentSize
  }
}

after this on storyboard assign DynamicHeight class to your UICollectionview. That's it.

Muhammad Ali
  • 1,055
  • 6
  • 11