Search code examples
iosswiftuicollectionviewnslayoutconstraint

Swift iOS -How to make CollectionView the size of its cells


I have a collectionView that can contain 2 to 5 cells. I want to pin the collection view to the bottom of it's parent vc but I want the collection view to be only the size of it's cells (similar to an Action Sheet).

If I wasn't;t using anchors this is how I would do it only setting its frame:

// this works fine but I just can't achieve this using anchors
cv.frame = CGRect(x: 0, y: view.frame.height - heightOfAllCells, width: view.frame.width, height: heightOfAllCells)

Using anchors how can I get the collectionView to be only the size of it's cells but still pinned to the bottom of it's parent view?

let cv: UICollectionView!
let myData = [String]()
let cellHeight: CGFloat = 50

override func viewDidLoad() {
    super.viewDidLoad()

    var heightOfAllCells = CGFloat(self.myData.count) * cellHeight

    //... instantiated cv layout and translateAutoResizingMask = false
    cv.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    cv.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

    cv.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true

    cv.topAnchor.constraint(equalTo: cv.bottomAnchor, constant: -heightOfAllCells).isActive = true

    cv.heightAnchor.constraint(equalToConstant: heightOfAllCells).isActive = true
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return myData.count
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: cellHeight)
}

Solution

  • You need to remove this constraint

      cv.topAnchor.constraint(equalTo: cv.bottomAnchor, constant: -heightOfAllCells).isActive = true