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

标签 ios swift uicollectionview nslayoutconstraint

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

如果我没有使用 anchor ,这就是我仅设置其框架的方法:

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

使用 anchor 如何使 collectionView 仅具有其单元格的大小,但仍固定在其父 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)
}

最佳答案

您需要删除此限制

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

关于ios - Swift iOS - 如何使 CollectionView 的单元格大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50859243/

相关文章:

ios - 导航 Controller 推送无法正常工作 ios 11

ios - 删除核心数据中的重复对象(快速)

ios - 未使用自定义 UICollectionViewLayout 调用 cellForItemAtIndexPath

swift - 标识运算符还可以检查命名类型是否相同,而不仅仅是引用相等

ios - 从多个 View Controller 输入数据时如何更新核心数据

ios - 如何使 UICollectionViewFlowLayout itemSize 动态显示屏幕大小

ios - 覆盖滚动指示器的 UICollectionView 单元格

ios - 如何在没有硬编码手动计算的情况下使用 UTC 时区偏移量来偏移 NSDate

ios - 什么相当于 iOS 中的 ContentObserver?

swift - 使用 os_log 记录函数参数或其他动态数据