Issue with placing cells in custom flow layout of UICollectionViews

拟墨画扇 提交于 2019-12-24 07:40:06

问题


I am trying to create a tag flow layout. To do this I followed a very nice tutorial https://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

I managed to create and customize the flow layout, but the cells are not aligned properly some times. Here is the screenshot from iphone 4S. I have two header sections also

As you can see in section 1, the tags are not placed correctly. I am not understanding what is causing this issue.

Here is my custom flow layout class

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
    }
}

So i need help in figuring out this issue.

Regards Ranjit

来源:https://stackoverflow.com/questions/38163448/issue-with-placing-cells-in-custom-flow-layout-of-uicollectionviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!