0

Hi I'm trying to set dynamic cell's height.

enter image description here

Here is my UICollectionViewCell

import UIKit
import Parse
import ActiveLabel
class UserShopDetailCell: UICollectionViewCell {

    @IBOutlet weak var postImg: UIImageView!

    @IBOutlet weak var likesLbl: UILabel!
    @IBOutlet weak var usernameLbl: UILabel!
    @IBOutlet weak var commentLbl: ActiveLabel!
    @IBOutlet weak var descriptionLbl: ActiveLabel!
    @IBOutlet weak var profileImg: UIImageView!
    @IBOutlet weak var timeLbl: UILabel!

    @IBOutlet weak var descriptionTop: NSLayoutConstraint!
    @IBOutlet weak var commentTop: NSLayoutConstraint!
    @IBOutlet weak var timeTop: NSLayoutConstraint!


    override func awakeFromNib() {



    }


}

And It is collectionviewcontroller

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {

    let cellsAcross: CGFloat = 3
    let spaceBetweenCells: CGFloat = 1
    let dim = (collectionView.bounds.width - (cellsAcross - 1) * spaceBetweenCells) / cellsAcross

    var width = 114.0


    if(isGridView==true){
        return CGSize(width: 114, height: 114)
    }
    else {



//I want set dynamic height...not constant values
        return CGSize(width: 375, height: 500)
    }


}




 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {



    if isGridView == false {

 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserShopDetailCell", for: indexPath) as! UserShopDetailCell

... ..... ......

  let basicHeight = cell.frame.size.width + 23 + cell.usernameLbl.frame.height + 1 + cell.likesLbl.frame.height

            let bottomHeight = cell.timeTop.constant + cell.timeLbl.frame.height + 12

        var dynamicHeight = basicHeight + bottomHeight

         cell.frame.size.height = dynamicHeight
        cell.sizeToFit()
        cell.sizeThatFits(CGSize(width: 375, height: dynamicHeight))
        cell.contentView.sizeThatFits(CGSize(width: 375, height: dynamicHeight))


return cell
}

}

enter image description here

As you can see.. white space is 500 height - dynamic height.

I want finally set cell's height from dynamic height values.

But When I set the CGSize then dynamic height is not working when is bigger than CGSize.

How Can I solve this problem?

Shawn Baek
  • 1,701
  • 3
  • 16
  • 31

1 Answers1

1

follow these steps to create self sizing cells on collectionview. No need to use sizeForItemAtIndexPath method when creating cells using estimatedItemSize and auto layout.

  1. set estimatedItemSize on collectionViewFlowlayout
  2. use auto layout to set correct constraint for your collectionviewcell subclass

refer the link and the tutorial on how to use self sizing cells using auto layout

here is the Github project link

Community
  • 1
  • 1
Suhit Patil
  • 10,286
  • 2
  • 42
  • 54