skip to Main Content

What is the way to set the equal size height for all cells in collection view?

I have this method:

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return getCellSize()
  }

  func getCellSize() -> CGSize {
    let screenWidth: CGFloat = UIScreen.main.bounds.width
    let spaceBetweenItems: CGFloat = CGFloat(2) * 10
    let width: CGFloat = (screenWidth - 10 - spaceBetweenItems) / CGFloat(3.0)
    return CGSize(width: width, height: CGFloat(140.0))
  }

And these are my customs cell constraints:
enter image description here
enter image description here

This is my actual output:
enter image description here

What is wrong in my code or is missing one constraint ?

2

Answers


  1. In storyboard with collection view: select your collection view -> go to size inspector -> change field "Estimate size" from "automatic" to "none"
    like here.
    But then if you text will be too large it will be clipped with dots like "Some large text..", so you can change field "Autoshrink" of your UILabel in attribute inspector to "Minimum Font Scale".

    Login or Signup to reply.
  2. create Constraint CollectionViewHeight.

    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    

    and then, try this Code.

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let height = collectionView.collectionViewLayout.collectionViewContentSize.height
        collectionViewHeight.constant = height
        self.view.layoutIfNeeded()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search