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