使用collectionview自定義標簽(默認兩行,左對齊蛛芥,間距相同口锭,橫向滾動)
需要自定義UICollectionViewFlowLayout
下面是實現代碼
import UIKit
class LeftLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = super.layoutAttributesForElements(in: rect)
var rowCollections = [CGFloat: [UICollectionViewLayoutAttributes]]()
for attributes in layoutAttributes ?? [] {
let minY = attributes.frame.minY
if rowCollections[minY] == nil {
rowCollections[minY] = [UICollectionViewLayoutAttributes]()
}
rowCollections[minY]?.append(attributes)
}
for (_, attributesArray) in rowCollections {
var xOffset: CGFloat = sectionInset.left
var rowHeight: CGFloat = 0
for attributes in attributesArray {
let itemWidth = attributes.frame.width
let itemHeight = attributes.frame.height
attributes.frame.origin.x = xOffset
xOffset += itemWidth + minimumInteritemSpacing
rowHeight = max(rowHeight, itemHeight)
// Adjust the height of the attributes to fit two lines
if attributesArray.count > 1 {
attributes.frame.size.height = rowHeight
}
}
}
return layoutAttributes
}
}