Search code examples
iosuicollectionviewcellsift

Auto collection view cell Height


I have a custom cell with a label. I get the text from the server, and the cell in the collection must choose the height so that all the text fits and is visible. Now I use this method, but I do not know how to change the height so that it adjusts.

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       
        return   CGSize(width: self.bounds.width, height: 90)
      
   }

Solution

  • Step 1:- Create a function to estimate the size of your text: This method will return a height value that will fit your string!

    private func estimateFrameForText(text: String) -> CGRect {
        //we make the height arbitrarily large so we don't undershoot height in calculation
        let height: CGFloat = 999
    
        let size = CGSize(width: yourDesiredWidth, height: height)
        let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(18, weight: UIFontWeightLight)]
    
        return NSString(string: text).boundingRectWithSize(size, options: options, attributes: attributes, context: nil)
    }
    

    Step 2: Use or override delegate method below:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        var height: CGFloat = 0
    
       //we are just measuring height so we add padding constant to give the label some room to breathe! 
        var padding: CGFloat = 10
    
    let stringFromViewModel = “Hello please pass your string here from array…”
        //estimate each cell's height
             height = estimateFrameForText(stringFromViewModel).height + padding
        return CGSize(width: yourDesiredWidth, height: height)
    }