UICollectionView简单的实现瀑布流 自定义UICollectionViewFlowLayout(页面要求第二个分区是瀑布流形式的 )(section)

本文介绍了一个自定义的UICollectionViewFlowLayout子类HotCVFlowLayout,用于实现页面第二个分区的瀑布流布局效果。通过对UICollectionViewLayoutAttributes的重写及调整,实现了不同宽度图片的自适应布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

页面要求第二个分区是瀑布流形式的 

//
//  HotCVFlowLayout.h
//  Zhouyi
//
//  Created by mac_os on 2021/11/18.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface HotCVFlowLayout : UICollectionViewFlowLayout

@end

NS_ASSUME_NONNULL_END

 

//
//  HotCVFlowLayout.m
//  Zhouyi
//
//  Created by mac_os on 2021/11/18.
//

#import "HotCVFlowLayout.h"

@interface HotCVFlowLayout ()


@end

@implementation HotCVFlowLayout
//1进行初始化
- (void)prepareLayout{
    [super prepareLayout];
    
}
//
////2 重写; 返回内容的大小
//- (CGSize)collectionViewContentSize{
//    
//}
//
//3 重写;方法返回rect中所有元素的布局属性,返回的是一个数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    //获取原本的布局数据
    NSArray *arr = [[NSArray alloc]initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES];


    //循环遍历所有布局数据
    for (UICollectionViewLayoutAttributes *attr in arr) {
        
       
        if(attr.indexPath.section == 1){
            CGFloat img_w = (SCREEN_WIDTH-10*2-10)/2;
            CGFloat img_d_h = 128/172.0*img_w;
            CGFloat img_l_h = 174/173.0*img_w;

            if (attr.indexPath.row == 0) {
                CGRect frame = attr.frame;
                frame = CGRectMake(frame.origin.x, frame.origin.y-(img_l_h-img_d_h)/2.0, frame.size.width, frame.size.height);

                attr.frame = frame;
            }else{
                if(attr.indexPath.row%2==0){
                    CGRect frame = attr.frame;
                    frame = CGRectMake(frame.origin.x, frame.origin.y-(img_l_h-img_d_h)+10, frame.size.width, frame.size.height);

                    attr.frame = frame;

                }
                
            }

            
        }
        
    }
    
    return arr;
}

////4 重写;方法返回对应的indexPath的位置的cell的布局属性
//- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
//    
//}

//7 重写;当边界发生变化时,是否应该刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}



@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值