Swift-collectionview自定义标签(横向)

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容