如何在集合视图中更改单元格的位置?

问题描述 投票:0回答:1

我在一个集合视图中有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坐标,使它们显示在集合视图的底部附近?

ios swift xcode uicollectionview cell
1个回答
0
投票

如果UICollectionView是静态的,则可以通过丢失顶部约束并将其赋予恒定的高度约束并将其约束到底部来将像元移至底部。方法如下:

修改此:

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

为此:

addConstraintsWithFormat("H:|[v0]|", views: collectionView)
addConstraintsWithFormat("V:[v0(100)]|", views: collectionView)
© www.soinside.com 2019 - 2024. All rights reserved.