繁体   English   中英

如何更改集合视图锡约束中单元格的 position?

[英]How to change the position of cells in a collection view tin constraints?

我在集合视图中有 4 个单元格,但是添加了约束后,它们出现在视图的右上角附近。 以下是这些单元格的代码:

class TopHomeMenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {


lazy var collectionView: UICollectionView = {

    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = UIColor.systemGreen
    cv.dataSource = self
    cv.delegate = self
    return cv
}()

let cellId = "cellId"

override init(frame: CGRect) {
    super.init(frame: frame)

    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)

    addSubview(collectionView)
    addConstraintsWithFormat("H:|[v0]|", views: collectionView)
    addConstraintsWithFormat("V:|[v0]|", views: collectionView)

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 4
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)

    cell.backgroundColor = .red

    return cell
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

有没有办法通过这些约束来改变单元格的 y 坐标,使它们出现在集合视图的底部附近?

如果UICollectionView是 static,您可以通过失去顶部约束并为其提供恒定高度约束并将其约束到底部来将单元格移动到底部。 就是这样:

修改这个:

addConstraintsWithFormat("H:|[v0]|", views: collectionView)
addConstraintsWithFormat("V:|[v0]|", views: collectionView)

对此:

addConstraintsWithFormat("H:|[v0]|", views: collectionView)
addConstraintsWithFormat("V:[v0(100)]|", views: collectionView)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM