登录 立即注册
金钱:

Code4App-iOS开发-iOS 开源代码库-iOS代码实例搜索-iOS特效示例-iOS代码例子下载-Code4App.com

MG--OC和Swift的瀑布流布局

[复制链接]
Tag:

项目介绍:

  • 瀑布流(OC和Swift)

  • 算封装的比较好。提供接口,只需要成为MGWaterFlayout的代理,即可在外界设置那个cell的间距,collection View 的inset等进行UI界面的布局,非常方便。

  • 效果

    1.png

2.png
瀑布流.gif

  • github网址:

OC源码查看

Swift源码项目查看


  • OC

    • .h

//  MGWaterflowLayout.h
//  MGPuBuLiuDemo
//  Created by ming on 16/6/9.
//  Copyright © 2016年 ming. All rights reserved.

#import <UIKit/UIKit.h>
@class MGWaterflowLayout;

#pragma mark - 协议
@protocol MGWaterflowLayoutDelegate <NSObject>
@optional
- (CGFloat)waterflowLayout:(MGWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSIndexPath *)indexPath itemWidth:(CGFloat)itemWidth;

@optional
- (CGFloat)columnCountInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
- (CGFloat)columnMarginInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
- (CGFloat)rowMarginInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
- (CGSize)layoutCollectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)layout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
@end



#pragma mark - MGWaterflowLayout
@interface MGWaterflowLayout : UICollectionViewFlowLayout
/** 代理 */
@property (nonatomic, weak) id<MGWaterflowLayoutDelegate> delegate;
@end
  • .m

//  MGWaterflowLayout.m
//  MGPuBuLiuDemo
//  Created by ming on 16/6/9.
//  Copyright © 2016年 ming. All rights reserved.

#import "MGWaterflowLayout.h"

/** 默认的列数 */
static const NSInteger MGDefaultColumnCount = 3;
/** 每一列之间的间距 */
static const CGFloat MGDefaultColumnMargin = 10;
/** 每一行之间的间距 */
static const CGFloat MGDefaultRowMargin = 10;
/** 边缘间距 */
static const UIEdgeInsets MGDefaultEdgeInsets = {10, 10, 10, 10};

@interface MGWaterflowLayout ()

/** 存放所有cell的布局属性 */
@property (nonatomic, strong) NSMutableArray *attrsArray;
/** 存放所有列的当前高度 */
@property (nonatomic, strong) NSMutableArray *columnHeights;

/** 每一行之间的间距 */
- (CGFloat)rowMargin;
/** 每一列之间的间距 */
- (CGFloat)columnMargin;
/** 列数 */
- (NSInteger)columnCount;
/** 边缘间距 */
- (UIEdgeInsets)edgeInsets;

@end

@implementation MGWaterflowLayout

#pragma mark - 常见数据处理
- (CGFloat)rowMargin
{
    if ([self.delegate respondsToSelector:@selector(rowMarginInWaterflowLayout:)]) {
        return [self.delegate rowMarginInWaterflowLayout:self];
    } else {
        return MGDefaultRowMargin;
    }
}

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

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

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


#pragma mark - 懒加载
- (NSMutableArray *)columnHeights
{
    if (!_columnHeights) {
        _columnHeights = [NSMutableArray array];
    }
    return _columnHeights;
}

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


- (void)prepareLayout{
    [super prepareLayout];
    
#warning 删除以前保存的高度
    [self.columnHeights removeAllObjects];
    for (NSInteger i = 0; i < self.columnCount; i++) {
        [self.columnHeights addObject:@(self.edgeInsets.top)];
    }
    
    
    // 清除之前所有的布局属性
    [self.attrsArray removeAllObjects];
    // 1.获取cell的个数
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    
    // 清除之前所有的布局属性
    [self.attrsArray removeAllObjects];

    // 2.遍历cell,把每一个布局添加到数组
    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];
    }
}



- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 创建布局属性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGFloat x,y,w,h;
    
//    w = (self.collectionView.frame.size.width - [self edgeInsets].left - [self edgeInsets].right - ([self columnCount] - 1) * MGDefaultColumnMargin)/[self columnCount];
     w = (self.collectionView.frame.size.width - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;
    
    // 通过代理可以设置高度
    if ([self.delegate respondsToSelector:@selector(waterflowLayout:heightForItemAtIndex:itemWidth:)]) {
        h = [self.delegate waterflowLayout:self heightForItemAtIndex:indexPath itemWidth:w];
    }else{
        h = 70 + arc4random_uniform(100);
    }

    // 取得所有列中高度最短的列
    NSInteger minHeightColumn = [self minHeightColumn];

//    x = MGDefaultEdgeInsets.left + minHeightColumn * (w + MGDefaultColumnMargin);
    x = self.edgeInsets.left + minHeightColumn * (w + self.columnMargin);

    y = self.edgeInsets.top + [self.columnHeights[minHeightColumn] floatValue] + self.rowMargin;

#warning 更改最短的一列
    [self.columnHeights replaceObjectAtIndex:minHeightColumn withObject:@(y+h)];

    attrs.frame = CGRectMake(x, y, w, h);
    
    return attrs;
}

/**
 * 决定cell的排布
 * 第一次显示时会调用一次
 * 用力拖拽时也会调一次
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.attrsArray;
}

/// 返回collectionView的滚动范围
- (CGSize)collectionViewContentSize{
    if (self.columnHeights.count == 0) {
        return CGSizeMake(0, 0);
    }
    
    // 获得最高的列
    NSInteger maxColum = [self maxHeightColumn];
    
    CGFloat height = [self.columnHeights[maxColum] floatValue] + MGDefaultEdgeInsets.bottom;
    CGFloat width = self.collectionView.frame.size.width;
    
    return CGSizeMake(width, height);
}

/// 取得所有列中高度最短的列
- (NSInteger)minHeightColumn{
    // 找出columnHeights的最小值
    NSInteger minHeightColum = 0;
    CGFloat minColumHeight = [self.columnHeights[0] floatValue];
    
    for (NSInteger i = 1; i < self.columnHeights.count; i++) {
        CGFloat tempHeight = [self.columnHeights[i] floatValue];
        
        if (tempHeight < minColumHeight) {
            minHeightColum = i;
            minColumHeight = tempHeight;
        }
    }
    return minHeightColum;
}

/// 取得所有列中高度最高的列
- (NSInteger)maxHeightColumn{
    // 找出columnHeights的最小值
    NSInteger maxHeightColumn = 0;
    CGFloat maxColumnHeight = [self.columnHeights[0] floatValue];
    
    for (NSInteger i = 1; i < self.columnHeights.count; i++) {
        CGFloat tempHeight = [self.columnHeights[i] floatValue];
        
        if (tempHeight > maxColumnHeight) {
            maxHeightColumn = i;
            maxColumnHeight = tempHeight;
        }
    }
    return maxHeightColumn;
}

///** 
// *  在元素的Interactive Movement期间被调用
// *  它带有target(目标元素)和先前的cell的indexPaths(索引地址)
// */
//- (UICollectionViewLayoutInvalidationContext *)invalidationContextForInteractivelyMovingItems:(NSArray<NSIndexPath *> *)targetIndexPaths withTargetPosition:(CGPoint)targetPosition previousIndexPaths:(NSArray<NSIndexPath *> *)previousIndexPaths previousPosition:(CGPoint)previousPosition{
//    UICollectionViewLayoutInvalidationContext *context = [super invalidationContextForInteractivelyMovingItems:targetIndexPaths withTargetPosition:targetPosition previousIndexPaths:previousIndexPaths previousPosition:previousPosition];
//    [self.collectionView moveItemAtIndexPath:previousIndexPaths[0] toIndexPath:targetIndexPaths[0]];
//    
//    [self.collectionView reloadData];
//    return context;
//}
//
///**
// *  这个与上一个函数类似,但它只在Interactive Movement结束后才调用
// *  它带有target(目标元素)和先前的cell的indexPaths(索引地址)
// */
//- (UICollectionViewLayoutInvalidationContext *)invalidationContextForEndingInteractiveMovementOfItemsToFinalIndexPaths:(NSArray<NSIndexPath *> *)indexPaths previousIndexPaths:(NSArray<NSIndexPath *> *)previousIndexPaths movementCancelled:(BOOL)movementCancelled{
//    UICollectionViewLayoutInvalidationContext *context = [super invalidationContextForEndingInteractiveMovementOfItemsToFinalIndexPaths:indexPaths previousIndexPaths:previousIndexPaths movementCancelled:movementCancelled];
//    [self.collectionView moveItemAtIndexPath:previousIndexPaths[0] toIndexPath:indexPaths[0]];
//    return context;
//}

@end



  • Swift

//  MGWaterFlowLayout.swift
//  MGDS_Swift
//  Created by i-Techsys.com on 17/1/21.
//  Copyright © 2017年 i-Techsys. All rights reserved.

import UIKit

// MARK: - 协议
@objc
protocol MGWaterFlowLayoutDelegate: NSObjectProtocol {
    @objc optional func waterflowLayout(waterflowLayout: MGWaterFlowLayout,heightForItemAtIndex indexPath: IndexPath,itemWidth: CGFloat) -> CGFloat
    @objc optional  func columnCountInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> Int
    @objc optional  func columnMarginInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> CGFloat
    @objc optional  func rowMarginInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> CGFloat
    @objc optional  func edgeInsetsInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> UIEdgeInsets  
    @objc optional func layoutCollectionView(collectionView: UICollectionView,layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath)
}


// MARK: - 默认参数
/** 默认的列数 */
private let MGDefaultColumnCount: Int = 3
/** 每一列之间的间距 */
private let MGDefaultColumnMargin: CGFloat = 10
/** 每一行之间的间距 */
private let MGDefaultRowMargin: CGFloat = 10
/** 边缘间距 */
private let MGDefaultEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)


class MGWaterFlowLayout: UICollectionViewFlowLayout {
    // MARK: - 自定义属性
    /** 存放所有cell的布局属性 */
    fileprivate var attrsArray = [UICollectionViewLayoutAttributes]()
    /** 存放所有列的当前高度 */
    fileprivate var columnHeights: [CGFloat] = [CGFloat]()
    /** MGWaterFlowLayout的代理 */
    weak var delegate: MGWaterFlowLayoutDelegate?
}

// MARK: - 边距和距离等
extension MGWaterFlowLayout {
    func rowMargin() -> CGFloat {
        if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.rowMarginInWaterflowLayout(waterflowLayout:))))! {
            return (delegate?.rowMarginInWaterflowLayout!(waterflowLayout: self))!
        }else {
            return MGDefaultRowMargin
        }
    }
    
    func columnMargin() -> CGFloat {
        if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.columnMarginInWaterflowLayout(waterflowLayout:))))! {
            return (delegate?.columnMarginInWaterflowLayout!(waterflowLayout: self))!
        }else {
            return MGDefaultColumnMargin
        }
    }
    
    func columnCount() -> Int {
        if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.columnCountInWaterflowLayout(waterflowLayout:))))! {
            return (delegate?.columnCountInWaterflowLayout!(waterflowLayout: self))!
        }else {
            return MGDefaultColumnCount
        }
    }
    
    func edgeInsets() -> UIEdgeInsets {
        if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.edgeInsetsInWaterflowLayout(waterflowLayout:))))! {
            return (delegate?.edgeInsetsInWaterflowLayout!(waterflowLayout: self))!
        }else {
            return MGDefaultEdgeInsets
        }
    }
}

// MARK: - 系统方法
extension MGWaterFlowLayout {
    override func prepare() {
        super.prepare()
        columnHeights.removeAll()
        
        for _ in 0..<self.columnCount() {
            self.columnHeights.append(self.edgeInsets().top)
        }
        
        // 清除之前所有的布局属性
        attrsArray.removeAll()
        
        // 1.获取cell的个数
       let count = (collectionView?.numberOfItems(inSection: 0))! as Int
        
        // 2.遍历cell,把每一个布局添加到数组
        for i in 0..<count {
            let indexPath = IndexPath(item: i, section: 0)
            let attrs = self.layoutAttributesForItem(at: indexPath)
            attrsArray.append(attrs!)
        }
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        super.layoutAttributesForItem(at: indexPath)
        // 创建布局属性
        let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        
        var x,y,w,h :CGFloat
        
        w = (self.collectionView!.frame.size.width - self.edgeInsets().left - self.edgeInsets().right - (CGFloat(self.columnCount()-1) * self.columnMargin())) / CGFloat(self.columnCount())
        
        // 通过代理可以设置高度
        if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.waterflowLayout(waterflowLayout:heightForItemAtIndex:itemWidth:))))! {
            h = self.delegate!.waterflowLayout!(waterflowLayout: self, heightForItemAtIndex: indexPath, itemWidth: w)
        }else {
            h = CGFloat(70) + CGFloat(arc4random_uniform(100))
        }
        
        
        // 取得所有列中高度最短的列
        let minHeightColumn = self.minHeightColumn()
        
        x = self.edgeInsets().left + CGFloat(minHeightColumn) * (w + self.columnMargin());
        
        y = self.edgeInsets().top + self.columnHeights[minHeightColumn] + self.rowMargin()
        
        // #warning 更改最短的一列
        self.columnHeights[minHeightColumn] = y + h
        
        attrs.frame = CGRect(x: x, y: y, width: w, height: h)
        
        return attrs;
    }
    
    /**
     * 决定cell的排布
     * 第一次显示时会调用一次
     * 用力拖拽时也会调一次
     */
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        super.layoutAttributesForElements(in: rect)
        return self.attrsArray
    }
    
    /// 返回collectionView的滚动范围
    override var collectionViewContentSize: CGSize {
        let _ = super.collectionViewContentSize
        if (self.columnHeights.count == 0) {
            return CGSize.zero
        }
        
        // 获得最高的列
        let maxColum = self.maxHeightColumn()
        
        let height: CGFloat = self.columnHeights[maxColum] + MGDefaultEdgeInsets.bottom;
        let width: CGFloat = self.collectionView!.frame.size.width;
        
        return CGSize(width: width, height: height)
    }
}

// MARK: - 自定义方法
extension MGWaterFlowLayout {
    /// 取得所有列中高度最短的列
    fileprivate func minHeightColumn() -> Int {
        // 找出columnHeights的最小值
        var minHeightColum: Int = 0
        var minColumHeight: CGFloat = self.columnHeights[0]
        
        for i in 1..<columnHeights.count {
            let tempHeight:CGFloat = self.columnHeights[i]
        
            if (tempHeight < minColumHeight) {
                minHeightColum = i;
                minColumHeight = tempHeight;
            }
        }
        return minHeightColum
    }
    
    /// 取得所有列中高度最高的列
   fileprivate func maxHeightColumn() -> Int {
        // 找出columnHeights的最高值
        var maxHeightColumn: Int = 0
        var maxColumnHeight: CGFloat = self.columnHeights[0]
        
        for i in 1..<columnHeights.count {
            let tempHeight:CGFloat = self.columnHeights[i]
            
            if (tempHeight < maxColumnHeight) {
                maxHeightColumn = i
                maxColumnHeight = tempHeight
            }
        }
        return maxHeightColumn
    }
}

  • 轻轻点击,关注我简书

轻轻点击,关注我简书

轻轻点击,关注我微博

浏览我的GitHub


  • 扫一扫,关注我

扫一扫,关注我.jpg

相关源码推荐:

我来说两句
*滑动验证:
所有评论(106)
code4app热心网友 2017-6-2 16:57:57
精华内容,楼主V5!
回复
565691320 2017-6-3 11:09:55
感谢分享,Code4App有你更精彩
回复
code4app热心网友 2017-6-3 13:07:29
正需要啊,感谢楼主无私分享!
回复
icjykeny 2017-6-3 20:35:23
淡定,淡定,淡定……
回复
icjykeny 2017-6-3 20:41:59
感谢分享,Code4App有你更精彩:)
回复
杨兴琛 2017-6-4 14:06:07
楼主用心了,内容非常精彩。
回复
code4app热心网友 2017-6-5 10:27:17
精华内容,楼主V5!
回复
code4app热心网友 2017-6-5 10:50:08
虽不明,但觉厉!
回复
code4app热心网友 2017-6-5 11:03:38
我只是路过打酱油的。
回复
提取码:  下载次数:205 状态:已购或VIP 售价:0(原价:10)金钱 下载权限:初级码农 
2848 0 205
联系我们
首页/微信公众账号投稿

帖子代码编辑/版权问题

QQ:435399051,742864542

如何获得代码达人称号?

代码贡献英雄榜
用户名 下载数
通过邮件订阅最新 Code4App 信息
上一条 /4 下一条
联系我们
关闭
合作电话:
13802416937
Email:
435399051@qq.com
商务市场合作/投稿
问题反馈及帮助
联系我们

广告投放| Github|申请友链|手机版|Code4App ( 粤ICP备15117877号-1 )

快速回复 返回顶部 返回列表