【问题标题】:Why is the last row of the collectionView not aligned properly?为什么collectionView的最后一行没有正确对齐?
【发布时间】:2020-08-08 19:55:00
【问题描述】:

我正在处理 collectionView 布局,如下所示:

但最后一行没有正确对齐不知道为什么?

这里是collectionView的设置代码:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(collectionViewCell.self)", for: indexPath) as? collectionViewCell {
        cell.imageView.backgroundColor = .black
        return cell
    }
    return UICollectionViewCell()
}

这里是流布局委托方法的实现:

let sectionInsets = UIEdgeInsets(top: 30.0, left: 20.0, bottom: 30.0, right: 20.0)

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {

    if indexPath.row == 2 { // This item should occupy the entire available width
        let paddingSpace = sectionInsets.left + sectionInsets.right
        let availableWidth = collectionView.frame.width - paddingSpace
        let widthPerItem = availableWidth
        return CGSize(width: widthPerItem, height: (widthPerItem / 2))
    }
    
    // adjust 2 cells in the single row
    let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
    let availableWidth = collectionView.frame.width - paddingSpace
    let widthPerItem = availableWidth / itemsPerRow
    
    return CGSize(width: widthPerItem, height: widthPerItem)
}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    insetForSectionAt section: Int) -> UIEdgeInsets {
    return sectionInsets
}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return sectionInsets.left
}

【问题讨论】:

    标签: ios swift collectionview flowlayout


    【解决方案1】:

    您所看到的对于流式布局来说是正常的。所有行都左对齐和右对齐除了,最后一行仅左对齐。这就像一本印刷书籍:段落的最后一行不会被隔开以触及右边距。

    【讨论】:

    • 谢谢,马特的回答。我不知道这是默认行为。有没有办法可以将最后一行与另一行相似对齐,使其看起来对称?
    • 顺便说一句,如果我从第二行中删除占据整个屏幕宽度的元素。然后最后一行看起来与另一行相似。这个问题是因为那一行吗?
    • 您需要子类化流布局类以更改其布局方式。或者,查看组合布局,这对几乎所有东西都更好。
    • 好吧,我建议的另一件事是,不要尝试如此动态地播放,如果您知道长单元何时到来,请使用三个部分而不是一个。现在每个都可以有自己的布局规则。通过在三个部分中使用组合布局,我可以轻松地创建 7 个单元格的布局。基本上,这是一个适合这项工作的工具的问题。
    • 我担心你会这么说。 :)
    【解决方案2】:

    我遇到了同样的问题。但我可以通过设置collectionView(_:layout:minimumInteritemSpacingForSectionAt:) 来修复。

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 1970-01-01
      • 2018-05-24
      • 2021-10-18
      • 2021-09-16
      • 2023-03-25
      • 2022-01-18
      • 2012-01-27
      • 2023-02-17
      相关资源
      最近更新 更多