greatsk
greatsk

Reputation: 23

how to uicollectionview height flexible

Use UICollectionView and want to show a small number of contents at once without scrolling

For example, if the number of contents is one or more, it can be five. However, if you set the UICollectionView height to 200 in case you have 5 contents when you have 1 content, you have 200 height. How would you like the height to be flexible depending on the number of content?

If the content is five, uicollectionView's height is 200, and if it's one, height is 40

Upvotes: 0

Views: 355

Answers (4)

iOS Geek
iOS Geek

Reputation: 4855

Two ways can be implemented -- Need to provide zero height or a height constraint to collectionView in storyboard

and now in View will Appear just try these two simple steps

  1. Get Contentsize height and Set frame height

    HotDealsCollectionView.frame.size.height = HotDealsCollectionView.contentSize.height

  2. Get Height On base of number of cells

    HotDealsCollectionView.frame.size.height = (Array.count * Static height if you provided)

Can call LayoutsIfNeeded() At end of both Options

Prefer First As Second will work if you are showing one in a row I mean Vertical CollectionView whereas in first option you will get its ContentSize height which you are actually looking for

NOTE: If in case your result is not getting expected like after adopting these options Frame size is not increased the just add some static height value at end like

HotDealsCollectionView.frame.size.height = HotDealsCollectionView.contentSize.height + 50

Hope it Helps

Upvotes: 0

iOS_MIB
iOS_MIB

Reputation: 1895

You can do something like below to achieve this:

Take a outlet of height constraint to your collection view and then change the height as desired for example

let height: CGFloat = (number of rows or content to show) * (heigh of row) //Calculation can differ according to needs
collectionViewHeightConstraint.constant = height
self.view.layoutIfNeeded()

I hope this may help you :)

Upvotes: 1

Faysal Ahmed
Faysal Ahmed

Reputation: 7669

You can do this by using this:

In viewWillAppear method update UICollectionView depend on content count

 let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
 layout.itemSize.height = content.count * 40
 self.collectionViewLayout = layout

Here I set an approximate value for each count. In this process, if the content count is 1 then collection view hight will be 40 and if content counts 5 then collection view height will be 200.

Upvotes: 0

mhmtkrgz
mhmtkrgz

Reputation: 86

You can disable scroll.

self.collectionView.scrollEnabled = NO;

Upvotes: 0

Related Questions