Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoresize UICollectionView height to adjust to its content size

Tags:

I have a UICollectionView, a button that creates a new cell in collection view. And I want UICollectionView to adjust it's size according to it's content size (when there are one or two cells then UICollectionView is short, if there are a lot of cell UICollectionView is big enough).

I know how to get content size:

collectionView.collectionViewLayout.collectionViewContentSize

But I have no idea where to use this value. I would appreciate if somebody help me to figure out how to make UICollectionView auto adjust it's height.

UPD: I published on GitHub a demo project that describes the problem: https://github.com/avokin/PostViewer

like image 388
AVokin Avatar asked Jun 09 '13 17:06

AVokin


2 Answers

I don't think content size is what you're after. I think you're wanting to adjust the amount of screen real estate consumed by the collection view, right? That's going to require adjustment of the frame. The content size includes the off-screen (scrolling) area as well as the on screen view.

I don't know of anything that would prevent you from just changing the frame size on the fly:

collectionView.frame = CGRectMake (x,y,w,h); [collectionView reloadData]; 

If I'm understanding you correctly.

like image 118
RegularExpression Avatar answered Oct 16 '22 18:10

RegularExpression


Use a height constraint for the collection view and update its value with the content height when needed. See this answer: https://stackoverflow.com/a/20829728/3414722

like image 43
sammalfix Avatar answered Oct 16 '22 18:10

sammalfix