美文网首页
iOS 瀑布流

iOS 瀑布流

作者: gaookey | 来源:发表于2020-08-29 08:00 被阅读0次
Swift
import UIKit

protocol SPWaterflowLayoutDelegate: NSObjectProtocol {
    func waterflowLayout(view: SPWaterflowLayout, heightForItemAtIndex: Int, itemWidth: CGFloat) -> CGFloat
    func columnCount(in view: SPWaterflowLayout) -> NSInteger
    func columnMargin(in view: SPWaterflowLayout) -> CGFloat
    func rowMargin(in view: SPWaterflowLayout) -> CGFloat
    func edgeInsets(in view: SPWaterflowLayout) -> UIEdgeInsets
}

extension SPWaterflowLayoutDelegate {
    func columnCount(in view: SPWaterflowLayout) -> NSInteger { return 2 }
    func columnMargin(in view: SPWaterflowLayout) -> CGFloat { return 10 }
    func rowMargin(in view: SPWaterflowLayout) -> CGFloat { return 10 }
    func edgeInsets(in view: SPWaterflowLayout) -> UIEdgeInsets { return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) }
}

class SPWaterflowLayout: UICollectionViewLayout {
    
    weak var delegate: SPWaterflowLayoutDelegate?
    
    private var attrsArray = [UICollectionViewLayoutAttributes]()
    private var columnHeights = [CGFloat]()
    private var contentHeight: CGFloat = 0
    
    private var columnCount: NSInteger {
        get {
            if let count = delegate?.columnCount(in: self) {
                return count
            }
            return 2
        }
    }
    
    private var columnMargin: CGFloat {
        get {
            if let margin = delegate?.columnMargin(in: self) {
                return margin
            }
            return 3
        }
    }
    
    private var rowMargin: CGFloat {
        get {
            if let margin = delegate?.columnMargin(in: self) {
                return margin
            }
            return 3
        }
    }
    
    private var edgeInsets: UIEdgeInsets {
        get {
            if let edge = delegate?.edgeInsets(in: self) {
                return edge
            }
            return UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
        }
    }
}

extension SPWaterflowLayout {
    
    override func prepare() {
        super.prepare()
        
        contentHeight = 0
        columnHeights.removeAll()
        
        for _ in 0..<columnCount {
            columnHeights.append(edgeInsets.top)
        }
        
        attrsArray.removeAll()
        guard let count = collectionView?.numberOfItems(inSection: 0) else {
            return
        }
        for i in 0..<count {
            if let attrs = layoutAttributesForItem(at: IndexPath(item: i, section: 0)) {
                attrsArray.append(attrs)
            }
        }
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attrsArray
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        
        let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        guard let collectionViewWidth = collectionView?.frame.width else {
            return attrs
        }
        
        let width = (collectionViewWidth - edgeInsets.left - edgeInsets.right - (CGFloat(columnCount) - 1) * columnMargin) / CGFloat(columnCount)
        guard let height = delegate?.waterflowLayout(view: self, heightForItemAtIndex: indexPath.item, itemWidth: width) else {
            return attrs
        }
        
        var destColumn: NSInteger = 0
        var minColumnHeight: CGFloat = columnHeights[0]
        
        for i in 0..<columnCount {
            let columnHeight = columnHeights[i]
            if minColumnHeight > columnHeight {
                minColumnHeight = columnHeight
                destColumn = i
            }
        }
        
        let x = edgeInsets.left + CGFloat(destColumn) * (width + columnMargin)
        var y = minColumnHeight
        
        if y != edgeInsets.top {
            y += rowMargin
        }
        
        attrs.frame = CGRect(x: x, y: y, width: width, height: height)
        
        columnHeights[destColumn] = attrs.frame.maxY
        
        let columnHeight = columnHeights[destColumn]
        if contentHeight < columnHeight {
            contentHeight = columnHeight
        }
        
        return attrs
    }
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: 0, height: contentHeight + edgeInsets.bottom)
    }
}
OC
#import <UIKit/UIKit.h>

@class SPWaterflowLayout;

@protocol SPWaterflowLayoutDelegate <NSObject>

@required

/// 高度
- (CGFloat)waterflowLayout:(SPWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth;

@optional

/// 竖排 数
- (CGFloat)columnCountInWaterflowLayout:(SPWaterflowLayout *)waterflowLayout;

/// 竖向 间距
- (CGFloat)columnMarginInWaterflowLayout:(SPWaterflowLayout *)waterflowLayout;

/// 横向 间距
- (CGFloat)rowMarginInWaterflowLayout:(SPWaterflowLayout *)waterflowLayout;

/// 边缘间距
- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(SPWaterflowLayout *)waterflowLayout;

@end

@interface SPWaterflowLayout : UICollectionViewLayout

@property (nonatomic, weak) id<SPWaterflowLayoutDelegate> delegate;

@end
#import "SPWaterflowLayout.h"

/// 默认的列数
static const NSInteger SPDefaultColumnCount = 3;

/// 每一列之间的间距
static const CGFloat SPDefaultColumnMargin = 10;

/// 每一行之间的间距
static const CGFloat SPDefaultRowMargin = 10;

/// 边缘间距
static const UIEdgeInsets SPDefaultEdgeInsets = {10, 10, 10, 10};

@interface SPWaterflowLayout()

/// 存放所有cell的布局属性
@property (nonatomic, strong) NSMutableArray *attrsArray;

/// 存放所有列的当前高度
@property (nonatomic, strong) NSMutableArray *columnHeights;

/// 内容的高度
@property (nonatomic, assign) CGFloat contentHeight;

- (CGFloat)rowMargin;

- (CGFloat)columnMargin;

- (NSInteger)columnCount;

- (UIEdgeInsets)edgeInsets;

@end

@implementation SPWaterflowLayout

- (CGFloat)rowMargin {
    if ([self.delegate respondsToSelector:@selector(rowMarginInWaterflowLayout:)]) {
        return [self.delegate rowMarginInWaterflowLayout:self];
    } else {
        return SPDefaultRowMargin;
    }
}

- (CGFloat)columnMargin {
    if ([self.delegate respondsToSelector:@selector(columnMarginInWaterflowLayout:)]) {
        return [self.delegate columnMarginInWaterflowLayout:self];
    } else {
        return SPDefaultColumnMargin;
    }
}

- (NSInteger)columnCount {
    if ([self.delegate respondsToSelector:@selector(columnCountInWaterflowLayout:)]) {
        return [self.delegate columnCountInWaterflowLayout:self];
    } else {
        return SPDefaultColumnCount;
    }
}

- (UIEdgeInsets)edgeInsets {
    if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterflowLayout:)]) {
        return [self.delegate edgeInsetsInWaterflowLayout:self];
    } else {
        return SPDefaultEdgeInsets;
    }
}

- (void)prepareLayout {
    [super prepareLayout];
    
    self.contentHeight = 0;
    
    // 清除以前计算的所有高度
    [self.columnHeights removeAllObjects];
    
    for (NSInteger i = 0; i < self.columnCount; i++) {
        [self.columnHeights addObject:@(self.edgeInsets.top)];
    }
    
    // 清除之前所有的布局属性
    [self.attrsArray removeAllObjects];
    
    // 开始创建每一个cell对应的布局属性
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    for (NSInteger i = 0; i < count; i++) {
        // 创建位置
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        // 获取indexPath位置cell对应的布局属性
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
        
        [self.attrsArray addObject:attrs];
    }
}

// 决定cell的排布
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attrsArray;
}

// 返回indexPath位置cell对应的布局属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 创建布局属性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    // collectionView的宽度
    CGFloat collectionViewW = self.collectionView.frame.size.width;
    // 设置布局属性的frame
    CGFloat w = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) /self.columnCount;
    CGFloat h = [self.delegate waterflowLayout:self heightForItemAtIndex:indexPath.item itemWidth:w];
    
    // 找出高度最短的那一列
    NSInteger destColumn = 0;
    CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
    
    for (NSInteger i = 1; i < self.columnCount; i++) {
        // 取得第i列的高度
        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
        
        if (minColumnHeight > columnHeight) {
            minColumnHeight = columnHeight;
            destColumn = i;
        }
    }
    
    CGFloat x = self.edgeInsets.left + destColumn * (w + self.columnMargin);
    CGFloat y = minColumnHeight;
    
    if (y != self.edgeInsets.top) {
        y += self.rowMargin;
    }
    attrs.frame = CGRectMake(x, y, w, h);
    
    // 更新最短那列的高度
    self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
    // 记录内容的高度
    CGFloat columnHeight = [self.columnHeights[destColumn] doubleValue];
    
    if (self.contentHeight < columnHeight) {
        self.contentHeight = columnHeight;
    }
    
    return attrs;
}

- (CGSize)collectionViewContentSize {
    return CGSizeMake(0, self.contentHeight + self.edgeInsets.bottom);
}

- (NSMutableArray *)columnHeights {
    if (!_columnHeights) {
        _columnHeights = [NSMutableArray array];
    }
    return _columnHeights;
}
- (NSMutableArray *)attrsArray {
    if (!_attrsArray) {
        _attrsArray = [NSMutableArray array];
    }
    return _attrsArray;
}

@end

相关文章

  • iOS UICollectionView autolayout

    iOS UICollectionView autolayout UICollectionViewCell 瀑布流加...

  • 关于自定义瀑布流的布局(Swift)

    瀑布流 UICollectionView Swift 最近整理以前iOS开发中用到的功能代码,发觉对瀑布流的布局有...

  • iOS使用UICollectionView实现瀑布流

    UICollectionView实现瀑布流 在iOS中可以实现瀑布流的目前已知的有2种方案: 使用UIScroll...

  • iOS瀑布流

    说来惭愧,使用collectionView这么久了,还从来没自己写过瀑布流,废话不多说,先上效果图: 数据来源 数...

  • iOS瀑布流

    参考 http://blog.csdn.net/yi_zz32/article/details/50520136将...

  • iOS - 瀑布流

    在最近小玩一下瀑布流中发现的一个小坑如图: Demo下载:WaterFall - 瀑布流布局

  • iOS瀑布流

    瀑布流 因为iOS提供UICollectionViewLayout的布局类不能实现瀑布流的效果,所以需要自定义一个...

  • iOS 瀑布流

    下面这些是外部封装的接口: @interface LRBWaterFallLayout : UICollectio...

  • iOS瀑布流

    瀑布流Demo 使用UICollectionView实现瀑布流 自定义UICollectionViewLayout...

  • iOS 瀑布流

    1.简单认识 瀑布流,又称瀑布流式布局。是比较流行的一种网站页面布局,视觉表现为参差不齐的多栏布局,随着页面滚动条...

网友评论

      本文标题:iOS 瀑布流

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