美文网首页iOS 技术分享
iOS - UICollectionView的item设置最大间

iOS - UICollectionView的item设置最大间

作者: Joh蜗牛 | 来源:发表于2019-04-28 09:46 被阅读0次

    新建一个layout文件,继承于UICollectionViewFlowLayout,在此文件中设置最大间距。
    .h文件:

    #import <UIKit/UIKit.h>
    
    @interface SortCellFlowLayout : UICollectionViewFlowLayout
    @property (nonatomic,assign) NSInteger maxCellSpacing;//最大间距
    @end
    
    

    .m文件

    #import "SortCellFlowLayout.h"
    
    @implementation SortCellFlowLayout
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    
        if (attributes.count <= 0) return attributes;
    
    
        CGFloat firstCellOriginX = ((UICollectionViewLayoutAttributes *)attributes[0]).frame.origin.x;
    CGFloat firstCellOriginY = ((UICollectionViewLayoutAttributes *)attributes[0]).frame.origin.y;
        
        for(int i = 1; i < attributes.count; i++) {
    
     UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
    UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
    
    // ========横向间距设置
           
            if (currentLayoutAttributes.frame.origin.x == firstCellOriginX) { // The first cell of a new row
                continue;
            }
    
            CGFloat prevOriginMaxX = CGRectGetMaxX(prevLayoutAttributes.frame);
            if ((currentLayoutAttributes.frame.origin.x - prevOriginMaxX) > self.maxCellSpacing) {
                CGRect frame = currentLayoutAttributes.frame;
                frame.origin.x = prevOriginMaxX + self.maxCellSpacing;
                currentLayoutAttributes.frame = frame;
            }
    
    
    //====== 纵向间距设置
            
            if (currentLayoutAttributes.frame.origin.y == firstCellOriginY) { // The first cell of a new row
                continue;
            }
            CGFloat prevOriginMaxY = CGRectGetMaxY(prevLayoutAttributes.frame);
            if ((currentLayoutAttributes.frame.origin.y - prevOriginMaxY) > self.maxCellSpacing) {
                CGRect frame = currentLayoutAttributes.frame;
                frame.origin.y = prevOriginMaxY + self.maxCellSpacing;
                currentLayoutAttributes.frame = frame;
            }
    
        }
        return attributes;
    }
    @end
    

    相关文章

      网友评论

        本文标题:iOS - UICollectionView的item设置最大间

        本文链接:https://www.haomeiwen.com/subject/ojirnqtx.html