user3766198
user3766198

Reputation: 109

Auto layout calculating same height for each collectionViewCell

So I have a collection view that uses a custom layout that I found on Github called CHTCollectionViewWaterfallLayout I like it so far, however I am looking to make the custom collection view cell I made dynamic in height, and I am having trouble connecting Auto Layout to calculate this. I shared a simple sample project on Github that generates random string sizes and displays them, only problem is that Auto Layout generates the same cell height for each Collection View Cell. The project can be found here.

To give you a run down of my thought process, I calculate the cell height by using the method CHTCollectionViewDelegateWaterfallLayout sizeForItemAtIndexPath. Since I also use the delegates method columnCountforSection my thought is since I provide a finite number of columns based on the orientation, I take the collectionView frame width and I divide by the number of columns to get me my width for the cell.

enter image description here

   func collectionView (collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        var cell = dict["heightCell"] as? CollectionViewCell

        let randomString = RadomStrings[indexPath.item]

        let float = CGFloat(columnCount)
        let width = collectionView.bounds.size.width / float
        if cell == nil {
            cell = NSBundle.mainBundle().loadNibNamed("CollectionViewCell", owner: self, options: nil)[0] as? CollectionViewCell
            dict["heightCell"] = cell
        }
        cell?.RandomStringLabel.text = randomString
        cell!.frame = CGRectMake(0, 0, CGRectGetWidth(collectionView.bounds), CGRectGetHeight(cell!.frame))
               cell!.setNeedsLayout()
             cell!.layoutIfNeeded()
        var size = cell?.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
        size?.width = width
     return CGSize(width: width, height: size!.height)
    }

My constraints are pretty basic. I have a constraint on each axis. One on the top of the content view, leading, trailing and bottom. I also have a height on the label that is greater than or equal to 45.

Using Auto Layout to calculate TableViewCell heights is easy to me and I like it because I like the DRY principle behind this height calculation approach. So I would like to keep this height calculation process the same throughout my app. CollectionViews are a relatively new layout process for me, so I would love to learn what I am doing wrong here. Hopefully I am clear for everyone, thanks!

Upvotes: 0

Views: 680

Answers (1)

user3766198
user3766198

Reputation: 109

I figured it out! What I didn't do is put a width constraint on the custom cell I created! Duh!

Upvotes: 1

Related Questions