Search code examples
iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

How to align UICollectionViewCell?


I am trying to build a UICollectionViewas tag flow layout according to this topic: http://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

It worked until the button action but there is one issue. As you can see at the picture below, custom UICollectionViewCell's don't align correctly as like as at the topic. I did everything same but FlowLayout.swift

enter image description here

I want to make equal gaps between these cells. But they are aligning like this.

You can find FlowLayout.swift below.

Can someone tell me how can I fix it?

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
    }


}

Solution

  • Solved.

    I changed the UICollectionView's layout flow to custom and set FlowLayout.swift as UICollectionView's class.