如何对齐 UICollectionViewCell?

Far*_*ruk 0 ios uicollectionview uicollectionviewcell uicollectionviewlayout swift

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

它一直工作到按钮动作,但有一个问题。正如您在下图中所看到的, customUICollectionViewCell不像主题那样正确对齐。我做的一切都一样,但是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
    }


}
Run Code Online (Sandbox Code Playgroud)

Joa*_*len 5

我知道这是一个旧线程,但问题仍然存在。这里的代码帮助我解决了我的问题,但我创建了一个更快速、更强大的版本。已经在 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 = $0
            // 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)