Swift iOS - 如何使 CollectionView 的单元格大小

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

我有一个可以包含 2 到 5 个单元格的 collectionView。我想将集合视图固定到它的父级 vc 的底部,但我希望集合视图仅为其单元格的大小(类似于 Action Sheet)。

如果我不使用锚点,这就是我只设置框架的方式:

// 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)

如何使用锚点使 collectionView 的大小仅为其单元格的大小,但仍固定在其父视图的底部?

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)
}

您需要删除此限制条件

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