Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizing a UICollectionViewCell that contains UITextView to fit the contentSize

Tags:

People also ask

How do I size a UITextView to its content?

It can be done using the UITextView contentSize . This will not work if auto layout is ON. With auto layout, the general approach is to use the sizeThatFits method and update the constant value on a height constraint. CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.

How do I make a collection view dynamic height?

Make-CollectionView-Height-Dynamic-According-to-ContentAdd a height constraint to your collection view. Set its priority to 999. Set its constant to any value that only makes it reasonably visible on the storyboard. Change the bottom equal constraint of the collection view to greater or equal.

What is swift Uicollectionview?

An object that manages an ordered collection of data items and presents them using customizable layouts.


I have a UICollectionView, where one of my UICollectionViewCells contains a UITextView. My goal is to autosize the UICollectionViewCell to fit the content of the text view.

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

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

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

But to do that within sizeForItemAtIndexPath, I need a pointer to the UITextView. To get that pointer, I find myself calling cellForItemAtIndexPath, but since that calls sizeForItemAtIndexPath it's an infinite loop.

I suspect I'm missing a way to pre-size the view and have the UICollectionView just respect that, but it appears to default to the 50x50 value that UICollectionViewFlowLayout defines.

Other (hack) ideas that I'm loathe to do:

  • Have another hidden UITextView that I can load the content into and get it's height.
  • Implement equivalent logic to calculate the content height on my own.

Thanks!