[英]Swift iOS -How to make CollectionView the size of its cells
I have a collectionView that can contain 2 to 5 cells. 我有一个collectionView,可以包含2到5个单元格。 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).
我想将集合视图固定在其父vc的底部,但我希望集合视图仅是其单元格的大小(类似于“动作表”)。
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? 使用锚点,如何使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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.