我有一个可以包含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)
}
答案 0 :(得分:0)
您需要删除此约束
cv.topAnchor.constraint(equalTo: cv.bottomAnchor, constant: -heightOfAllCells).isActive = true