collectionView item 右靠齐

此篇主要针对 collectionView item 对齐总结一下:

先上效果图:

1、直接pod 一个插件即可

详细文档:https://github.com/mokagio/UICollectionViewLeftAlignedLayout

在用到的.m文件中执行两步即可:

一导入:

#import "UICollectionViewLeftAlignedLayout.h"

二执行:

UICollectionViewLeftAlignedLayout *layout = [[UICollectionViewLeftAlignedLayout alloc] init];
你的collectionView.collectionViewLayout = layout;

2、使用自定布局,继承UICollectionViewFlowLayout,并重写layoutAttributesForElements方法

一继承:

在用到的.h文件中执行继承:

二重写:

class SelectedClassesViewFlowLayout: UICollectionViewFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 1.获取系统计算好的attributes
        guard let systemAttribues = super.layoutAttributesForElements(in: rect) else {return nil}
        let maximumSpacing = super.minimumInteritemSpacing
        // 2. 遍历
        systemAttribues.enumerated().forEach({ (arguments) in
            let (offset, attribute) = arguments
            if offset == 0 {return}
            // 2.1 获取当前的attributes
            let previewLayoutAttributes = systemAttribues[offset - 1]
            let currentLayoutAttributes = attribute
            // 2.2 获取位置
            let previewX = previewLayoutAttributes.frame.maxX
            let previewY = previewLayoutAttributes.frame.maxY
            let currentY = currentLayoutAttributes.frame.maxY
            // 2.3 改变当前的frame
            var frame = currentLayoutAttributes.frame
            frame.origin.x = previewY == currentY ? previewX + maximumSpacing : 0
            currentLayoutAttributes.frame = frame
        })
        return systemAttribues
    }
}

3、修改 Item 布局

一 Item长度固定情况:通过      屏幕长度/item长度 = 每行个数,最后给item两种布局的情况即可解决。

一 Item长度不固定情况:通过     建议用第一种方法处理。

猜你喜欢

转载自blog.csdn.net/Harvey_DHui/article/details/88091624
今日推荐