如何对齐 UICollectionViewCell?

How to align UICollectionViewCell?

我正在尝试根据以下主题构建一个 UICollectionViewas 标签流布局:http://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

在按钮操作之前一直有效,但有一个问题。如下图所示,自定义 UICollectionViewCell 没有像主题那样正确对齐。我做了同样的事情,但 FlowLayout.swift

我想在这些单元格之间设置相等的间距。但他们是这样排列的。

您可以在下面找到 FlowLayout.swift

谁能告诉我该如何解决?

import Foundation
import UIKit

class FlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        let attributesForElementsInRect = super.layoutAttributesForElementsInRect(rect)
        var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()

        var leftMargin : CGFloat = 0.0

        for attributes in attributesForElementsInRect! {
            let refAttributes = attributes
            // assign value if next row
            if (refAttributes.frame.origin.x == self.sectionInset.left) {
                leftMargin = self.sectionInset.left
            } else {
                // set x position of attributes to current margin
                var newLeftAlignedFrame = refAttributes.frame
                newLeftAlignedFrame.origin.x = leftMargin
                refAttributes.frame = newLeftAlignedFrame
            }
            // calculate new value for current Fmargin
            leftMargin += refAttributes.frame.size.width + 8
            newAttributesForElementsInRect.append(refAttributes)
        }

        return newAttributesForElementsInRect
    }


}

已解决。

我将 UICollectionView 的布局流程更改为自定义,并将 FlowLayout.swift 设置为 UICollectionView 的 class。

我知道这是一个旧线程,但问题仍然存在。这里的代码帮助我解决了我的问题,但我创建了一个更快速、更健壮的版本。已经使用 Swift 5.1 和 iOS 13.

进行了测试
// A collection view flow layout in which all items get left aligned
class LeftAlignedFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let originalAttributes = super.layoutAttributesForElements(in: rect) else {
            return nil
        }
        var leftMargin: CGFloat = 0.0
        var lastY: Int = 0
        return originalAttributes.map {
            let changedAttribute = [=10=]
            // Check if start of a new row.
            // Center Y should be equal for all items on the same row
            if Int(changedAttribute.center.y.rounded()) != lastY {
                leftMargin = sectionInset.left
            }
            changedAttribute.frame.origin.x = leftMargin
            lastY = Int(changedAttribute.center.y.rounded())
            leftMargin += changedAttribute.frame.width + minimumInteritemSpacing
            return changedAttribute
        }
    }
}