LWLCollectionViewHorizontalLayout.m 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // DDCollectionViewHorizontalLayout.m
  3. // TestCollectionView
  4. //
  5. // Created by 刘卫林 on 15/08/27.
  6. #import"LWLCollectionViewHorizontalLayout.h"
  7. @implementation LWLCollectionViewHorizontalLayout
  8. - (void)prepareLayout
  9. {
  10. [super prepareLayout];
  11. //self.rowCount = 2;
  12. //self.itemCountPerRow = 5;
  13. self.allAttributes = [NSMutableArray array];
  14. NSUInteger count = [self.collectionView numberOfItemsInSection:0];
  15. for (NSUInteger i = 0; i<count; i++) {
  16. NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
  17. UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
  18. [self.allAttributes addObject:attributes];
  19. }
  20. }
  21. - (CGSize)collectionViewContentSize {
  22. return [super collectionViewContentSize];
  23. }
  24. - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
  25. NSUInteger item = indexPath.item;
  26. NSUInteger x;
  27. NSUInteger y;
  28. [self targetPositionWithItem:item resultX:&x resultY:&y];
  29. NSUInteger item2 = [self originItemAtX:x y:y];
  30. NSIndexPath *theNewIndexPath = [NSIndexPath indexPathForItem:item2 inSection:indexPath.section];
  31. UICollectionViewLayoutAttributes *theNewAttr = [super layoutAttributesForItemAtIndexPath:theNewIndexPath];
  32. theNewAttr.indexPath = indexPath;
  33. return theNewAttr;
  34. }
  35. - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
  36. NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
  37. NSMutableArray *tmp = [NSMutableArray array];
  38. for (UICollectionViewLayoutAttributes *attr in attributes) {
  39. for (UICollectionViewLayoutAttributes *attr2 in self.allAttributes) {
  40. if (attr.indexPath.item == attr2.indexPath.item) {
  41. [tmp addObject:attr2];
  42. break;
  43. }
  44. }
  45. }
  46. return tmp;
  47. }
  48. // 根据 item 计算目标item的位置
  49. // x 横向偏移 y 竖向偏移
  50. - (void)targetPositionWithItem:(NSUInteger)item
  51. resultX:(NSUInteger *)x
  52. resultY:(NSUInteger *)y {
  53. NSUInteger page = item/(self.itemCountPerRow*self.rowCount);
  54. NSUInteger theX = item % self.itemCountPerRow + page * self.itemCountPerRow;
  55. NSUInteger theY = item / self.itemCountPerRow - page * self.rowCount;
  56. if (x != NULL) {
  57. *x = theX;
  58. }
  59. if (y != NULL) {
  60. *y = theY;
  61. }
  62. }
  63. // 根据偏移量计算item
  64. - (NSUInteger)originItemAtX:(NSUInteger)x
  65. y:(NSUInteger)y {
  66. NSUInteger item = x * self.rowCount + y;
  67. return item;
  68. }
  69. @end