0

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

如果我不使用锚点,我会这样做,只设置它的框架:

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

1 回答 1

0

您需要删除此约束

  cv.topAnchor.constraint(equalTo: cv.bottomAnchor, constant: -heightOfAllCells).isActive = true
于 2018-06-14T14:01:14.747 回答