Manage Collection View Cell Height Dynamic According To Text Label Data

Updated 31 July 2019

Save

In most of the times we take label inside the collection view.  And we want the height of collection view exactly equals to label data height, because it will not look good if label data height is less than collection view cell, it will show a blank space and if label data height is more than collection view then it will truncate the data.

Here I am discussing about how to manage collection view cell height according to text label data.

Follow the steps :

Step 1: Go to Collection View cell class and create the outlet of label.

Step 2: Now go to MainViewController and create the outlet of collection view.

Step 3: Now create the extension to calculate the height of the label.

 

Step 4: Now Register the collection view cell so that we can use.

Step 5: After register the collection view cell write their All delegate and datasource method inside main controller class.

Step 6: Now your collection view cell height will automatically increase after calculating the height of label.

 

Conclusion

So please follow the above step and and if you have any issue or suggestion you can leave your query/suggestion in the comment section I will try to solve that.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


3 comments

  • Hafiz
    Error in this Line
    return text.height(withWidth: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: 17))
    label has no member height
    • Debabrata Roy (Moderator)

    • Debabrata Roy
      Use this extension
      extension String {
      func height(withWidth width: CGFloat, font: UIFont) -> CGFloat {
      let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
      let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)

      return ceil(boundingBox.height)
      }

      }

  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home