我正在尝试创建标签流布局。为此,我遵循了一个非常好的教程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
}
}
所以我需要帮助来解决这个问题。
问候兰吉特