搜索
您的当前位置:首页正文

关于collectionView的流水布局的分页横向显示

来源:二三娱乐

有时候我们会用到这样的效果:

                                                          第一页

                                                           第二页

可当你选择用collectionView实现的时候就会发现有些不同 现实是这样的:

                                                          第二页

这时候需要重写一下UICollectionViewFlowLayout  直接上代码  ~~~~~~~也请大神指正

#import "llblayout.h"

@interface llblayout ()

@property (strong, nonatomic) NSMutableArray *allAttributesArr;

@end

@implementation llblayout

/**

这里支持一个section numberOfItemsInSection:0 这里写死为0

self.allAttributesArr 拿到所有Item的属性

*/

- (void)prepareLayout

{

[super prepareLayout];

self.allAttributesArr = [NSMutableArray array];

NSUInteger count = [self.collectionView numberOfItemsInSection:0];

for (NSUInteger i = 0;i<count;i++{

NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];

UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];

[self.allAttributesArr addObject:attributes];

}

}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

{

NSUInteger item = indexPath.item;

NSUInteger x;

NSUInteger y;


[self targetPositionWithItem:item resultX:&x resultY:&y andWith:indexPath];

NSUInteger item2 = [self originItemAtX:x y:y];

这两个方法我没记错的话 (欢迎指正哈,写的太早了忘了)

当上面传来一个item 从0-----9吧

他会算出每个item的在横向排列中的新的位置

比如说

1  4 7                             1  2  3  

2  5 8 --------》那么在 4  5  6       这种排法中 原来的第2的位置 就是第4个对应的位置 我

3  6  9                             7 8  9       我们算出第四个的位置 复制给第二个就好


NSIndexPath *theNewIndexPath = [NSIndexPath indexPathForItem:item2 inSection:indexPath.section];

UICollectionViewLayoutAttributes *theNewAttr = [super layoutAttributesForItemAtIndexPath:theNewIndexPath];

这个方法算出来第4个的位置UICollectionViewLayoutAttributes 包含了每个item的位置信息

可以打印出来


theNewAttr.indexPath = indexPath;

把第四个的位置付给第二个 


return theNewAttr;

}

- (void)targetPositionWithItem:(NSUInteger)item

resultX:(NSUInteger *)x

resultY:(NSUInteger *)y andWith:(NSIndexPath *)indexpath

{

//这里有个问题的强调下  items 得是(self.itemCountsOneRow*self.rows) 他们的整数倍,而我的一般做法 是不够整数倍的话就传入空的模型 来凑够

NSUInteger page = item/(self.itemCountsOneRow*self.rows);

//    rows          .h文件的一个属性 外界传入 表示有几行

//    itemCountsOneRow    .h文件的一个属性 外界传入 表示每行有几个

NSUInteger theX = item % self.itemCountsOneRow + page * self.itemCountsOneRow;

NSUInteger theY = item / self.itemCountsOneRow - page * self.rows;

if (x != NULL) {

*x = theX;

}

if (y != NULL) {

*y = theY;

}

}

// 根据偏移量计算item

- (NSUInteger)originItemAtX:(NSUInteger)x

y:(NSUInteger)y

{

NSUInteger item = x * self.rows + y;

return item;

}

Top