本着想做一个横向滑动的视图,可是用了collectionView数据是纵向加载,如何让collectionView横向滑动,并且横向加载呢?自定义UICollectionViewFlowLayout
代码如下:
```
#import
@interfaceGiftCollectionViewLayout :UICollectionViewFlowLayout
//一行中cell的个数
@property(nonatomic,assign)NSUIntegeritemCountPerRow;
//一页显示多少行
@property(nonatomic,assign)NSUIntegerrowCount;
@property(strong,nonatomic)NSMutableArray*allAttributes;
@end
```
```
#import"GiftCollectionViewLayout.h"
@interfaceGiftCollectionViewLayout()
@end
@implementationGiftCollectionViewLayout
-(instancetype)init
{
if(self= [superinit])
{
}
returnself;
}
- (void)prepareLayout
{
[superprepareLayout];
self.rowCount=2;
self.itemCountPerRow=4;
self.allAttributes= [NSMutableArrayarray];
NSUIntegercount = [self.collectionViewnumberOfItemsInSection:0];
for(NSUIntegeri =0; i
NSIndexPath*indexPath = [NSIndexPathindexPathForItem:iinSection:0];
UICollectionViewLayoutAttributes*attributes = [selflayoutAttributesForItemAtIndexPath:indexPath];
[self.allAttributesaddObject:attributes];
}
}
- (CGSize)collectionViewContentSize
{
return[supercollectionViewContentSize];
}
- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath*)indexPath
{
NSUIntegeritem = indexPath.item;
NSUIntegerx;
NSUIntegery;
[selftargetPositionWithItem:itemresultX:&xresultY:&y];
NSUIntegeritem2 = [selforiginItemAtX:xy:y];
NSIndexPath*theNewIndexPath = [NSIndexPathindexPathForItem:item2inSection:indexPath.section];
UICollectionViewLayoutAttributes*theNewAttr = [superlayoutAttributesForItemAtIndexPath:theNewIndexPath];
theNewAttr.indexPath= indexPath;
returntheNewAttr;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray*attributes = [superlayoutAttributesForElementsInRect:rect];
NSMutableArray*tmp = [NSMutableArrayarray];
for(UICollectionViewLayoutAttributes*attrinattributes) {
for(UICollectionViewLayoutAttributes*attr2inself.allAttributes) {
if(attr.indexPath.item== attr2.indexPath.item) {
[tmpaddObject:attr2];
break;
}
}
}
returntmp;
}
//根据item计算目标item的位置
// x横向偏移y竖向偏移
- (void)targetPositionWithItem:(NSUInteger)item
resultX:(NSUInteger*)x
resultY:(NSUInteger*)y
{
NSUIntegerpage = item/(self.itemCountPerRow*self.rowCount);
NSUIntegertheX = item %self.itemCountPerRow+ page *self.itemCountPerRow;
NSUIntegertheY = item /self.itemCountPerRow- page *self.rowCount;
if(x !=NULL) {
*x = theX;
}
if(y !=NULL) {
*y = theY;
}
}
//根据偏移量计算item
- (NSUInteger)originItemAtX:(NSUInteger)x
y:(NSUInteger)y
{
NSUIntegeritem = x *self.rowCount+ y;
returnitem;
}
items 必须为 row * section 的整数倍,有待改善!
```