Проблема с размещением ячеек в пользовательском макете потока UICollectionViews

Я пытаюсь создать макет потока тегов. Для этого я следовал очень хорошему руководству https://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

Мне удалось создать и настроить макет потока, но несколько раз ячейки не выравнивались должным образом. Вот скриншот с iphone 4S. У меня также есть два раздела заголовка

введите здесь описание изображения

Как вы можете видеть в разделе 1, теги расставлены неправильно. Я не понимаю, что вызывает эту проблему.

Вот мой пользовательский класс макета потока

import UIKit

class FlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()        
        // unwrap super's attributes
        guard let attributesForElementsInRect = super.layoutAttributesForElementsInRect(rect) else { return nil }

        // modify attributes

        var leftMargin: CGFloat = 8.0;

        for attributes in attributesForElementsInRect {

            let itemAttributesCopy = attributes.copy() as! UICollectionViewLayoutAttributes

           print("attCopy",itemAttributesCopy.frame.size.width)
            print("left",leftMargin)
            print("collWidth",self.collectionView?.frame.size.width)

            print("sectionInset",self.sectionInset.left)

            if( itemAttributesCopy.frame.size.width + leftMargin > self.collectionView?.frame.size.width)
            {
                leftMargin = 8.0
            }
            if (itemAttributesCopy.frame.origin.x == self.sectionInset.left) {
                leftMargin = self.sectionInset.left
            } else {

                 print("itemAttributeCopy",itemAttributesCopy.frame)

                var newLeftAlignedFrame = itemAttributesCopy.frame
                newLeftAlignedFrame.origin.x = leftMargin
                itemAttributesCopy.frame = newLeftAlignedFrame
                 print("newFrame",newLeftAlignedFrame)
            }
            leftMargin += itemAttributesCopy.frame.size.width + 8
             print("finalleftMargin",leftMargin)



            newAttributesForElementsInRect.append(itemAttributesCopy)
        }

        return newAttributesForElementsInRect
    }
}

Так что мне нужна помощь в выяснении этого вопроса.

С уважением Ранджит


person Ranjit    schedule 02.07.2016    source источник