3
votes

I am using UICollectionView and in it my cells have auto width based on the content(text size) e.g. first row might contain 8 items and 2nd row might contains only 1. This is working fine.

I want to set the height of my UICollectionView to show all the available items but not more(not the empty space at the bottom...). If I use auto layout than I have to set the height or bottom align constraint.

But in this way the height will be fixed. Is there any way I can get number of rows in and calculate height dynamically?

Here is what my story board look like:

enter image description here

1

1 Answers

1
votes

You could use fixed height constraint at design time and than change it at runtime when deferred height value calculated. Height constraint need to be referenced in code and than needs to be changed with your calculated height.

// Height constraint of collection view
@IBOutlet weak var heightContstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    setHeightOfCollectionView()
}

func setHeightOfCollectionView() {
    // Calculate height of collection view depending on collection item count
    let calculatedHeight:CGFloat = 500.0

    heightContstraint.constant = calculatedHeight
}

You should check the images below that demonstrate how to do. Hope it would help.

enter image description here