Determining the size of a UICollectionViewCell containing a UITextView to match the content

I have a UICollectionView where one of my UICollectionViewCells contains a UITextView. My goal is to automate the UICollectionViewCell to match the contents of the text view.

I have an overridden collection of View: sizeForItemAtIndexPath, but I'm struggling to get the content height value for a text view without creating an infinite loop.

Typically, to authorize a UITextView, I would do something like the following:

CGRect frame = textView.frame; frame.size.height = textView.contentSize.height; textView.frame = frame; 

But for this in sizeForItemAtIndexPath I need a pointer to a UITextView. To get this pointer, I find myself calling cellForItemAtIndexPath, but since it calls sizeForItemAtIndexPath, this is an infinite loop.

I suspect that I am missing the ability to pre-size the view, and the UICollectionView just respects this, but by default it matches the 50x50 value that defines the UICollectionViewFlowLayout.

Other (hack) ideas that I don't like:

  • There is another hidden UITextView that I can load into the content and get it.
  • Introduce equivalent logic to calculate the height of the content yourself.

Thanks!

+8
ios cocoa-touch uitextview uicollectionview uicollectionviewcell
source share
1 answer

You can set the collection view delegate to the text view delegate as well, and in textViewDidChange: update the property containing the latest height computed from textView.textContainer and textView.textContainerInset . Then you simply reference this property in sizeForItemAtIndexPath: In this case, you will also want to do some cell reloading and perhaps the layout is invalid each time the value of this property is about to change.

+4
source share

All Articles