【问题标题】:How to change the position of cells in a collection view tin constraints?如何更改集合视图锡约束中单元格的位置?
【发布时间】:2020-06-12 02:44:36
【问题描述】:

我在一个集合视图中有 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】:

    如果UICollectionView 是静态的,您可以通过失去顶部约束并为其提供恒定高度约束并将其约束到底部来将单元格移动到底部。方法如下:

    修改这个:

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

    到这里:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多