iOS常用

iOS商城类常用的菜单自定义 Layout

2021-03-16  本文已影响0人  9岁就很6

点h



@interface EGUHorizontalPageableLayout : UICollectionViewFlowLayout
///  一行中 cell 的个数
@property (nonatomic, assign) NSUInteger itemCountPerRow;

///    一页显示多少行
@property (nonatomic, assign) NSUInteger rowCount;
@end


点m

#import “EGUHorizontalPageableLayout.h”

@implementation EGUHorizontalPageableLayout
- (instancetype)init
{
    if (self = [super init]) {
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
}

- (CGSize)collectionViewContentSize
{
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    CGFloat rows = count / (self.rowCount * self.itemCountPerRow  * 1.0);
    return CGSizeMake(ceilf(rows) * SCREEN_WIDTH , 1);
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSUInteger item = indexPath.item;

    //创建布局实例
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    attrs.frame = [self targetPositionWithItem:item];
    
    return attrs;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
     NSMutableArray *arrayM = [NSMutableArray array];
       NSInteger count = [self.collectionView numberOfItemsInSection:0];
       
       //给每一个item创建并设置布局属性
       for (int i = 0; i < count; i++)
       {
           //创建item的布局属性
           UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
           
            [arrayM addObject:attrs];
       }
       return arrayM;
}


- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}


// 根据 item 计算目标item的位置
// x 横向偏移  y 竖向偏移
- (CGRect)targetPositionWithItem:(NSUInteger)item
{
    NSInteger page = item/(self.itemCountPerRow*self.rowCount) * SCREEN_WIDTH;
    CGFloat xOffset = self.sectionInset.left;
    CGFloat yOffset = self.sectionInset.top;
    NSInteger theX = item % self.itemCountPerRow * (self.itemSize.width +  self.minimumLineSpacing) + page + xOffset;
    NSInteger theY = (item % (self.itemCountPerRow*self.rowCount)) / self.itemCountPerRow * (self.itemSize.height + self.minimumInteritemSpacing) + yOffset;
    return CGRectMake(theX, theY, self.itemSize.width, self.itemSize.height);
    
}
@end

使用

EGUHorizontalPageableLayout *layout = [[EGUHorizontalPageableLayout alloc]init];
        layout.sectionInset = UIEdgeInsetsMake(0, 16, 16, 16);
        layout.itemSize = CGSizeMake(SCREEN_WIDTH / 5, 70);
        layout.minimumLineSpacing = 26;
        layout.minimumInteritemSpacing = 4;
        layout.itemCountPerRow = 5;
        layout.rowCount = 2;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

效果图

image.png
上一篇下一篇

猜你喜欢

热点阅读