简体   繁体   中英

Update UICollectionView height based on content

UICollectionView height not updating properly based on content. How to update height

My code :

collectionViewArray.append(trimmedStrig!)
        DispatchQueue.main.async {
            if self.collectionViewArray.count == 1 {
                self.collectionViewHeight.constant = self.collectionView.contentSize.height + 50
                print(self.collectionViewHeight.constant)
            } else if self.collectionViewArray.count > 1 {
                self.collectionViewHeight.constant = self.collectionView.contentSize.height
                print(self.collectionViewHeight.constant)
            }
            self.collectionView.reloadData()
        }

//Fix collection view cell height and width
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: 100, height: 50)
}

When create 1st cell it's not displaying that cell, that's why I added 50 and when cell entered into second row again it's not updating height, but when 2nd row 2nd cell created in that Time height updated. Why I don't know?

Add this line in code:-

collectionView.translatesAutoresizingMaskIntoConstraints = true
  • eg
 override func viewDidAppear(_ animated: Bool)
 {
      super.viewDidAppear(animated)
      if self.collectionViewArray.count == 1 
      {
          self.collectionViewHeight.constant = self.collectionView.contentSize.height + 50
          print(self.collectionViewHeight.constant)
      }
      else if self.collectionViewArray.count > 1 
      {
           self.collectionViewHeight.constant = self.collectionView.contentSize.height
           print(self.collectionViewHeight.constant)
       }
            collectionView.translatesAutoresizingMaskIntoConstraints = true //Here
            self.collectionView.reloadData()            
   }

Try this one its may be helpful for you

self.collView.reloadData()
self.collView.performBatchUpdates({}) { (complition) in
            self.cnsHeightCollView.constant = self.collView.contentSize.height
        }

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