CollectionViewSpaceLayout.m 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // CollectionViewSpaceLayout.m
  3. // xiaoli
  4. //
  5. // Created by zjh on 16/9/27.
  6. // Copyright © 2016年 zjh. All rights reserved.
  7. //
  8. #import "CollectionViewSpaceLayout.h"
  9. @interface CollectionViewSpaceLayout ()
  10. {
  11. //内容大小
  12. CGSize _contentSize;
  13. }
  14. //保存cell详细信息
  15. @property (nonatomic,strong) NSMutableArray *itemAttributes;
  16. @end
  17. @implementation CollectionViewSpaceLayout
  18. - (instancetype)init
  19. {
  20. self = [super init];
  21. if (self) {
  22. //设置默认信息
  23. _sectionInsets = UIEdgeInsetsZero;
  24. _interitemSpacing = 10;
  25. _lineSpacing = 10;
  26. }
  27. return self;
  28. }
  29. //1.布局cell的
  30. - (void)prepareLayout
  31. {
  32. self.delegate = (id<SpaceLayoutDelegate>)self.collectionView.delegate;
  33. _itemAttributes = [NSMutableArray array];
  34. //cell的x,y,宽度,高度
  35. CGFloat xOffset = _sectionInsets.left;
  36. CGFloat yOffset = _sectionInsets.top;
  37. //获取指定组的cell的个数
  38. NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:0];
  39. //collectionView的宽
  40. CGFloat collectionViewWidth = self.collectionView.frame.size.width;
  41. //计算每个cell的位置
  42. for (int i = 0; i < numberOfItems; i ++)
  43. {
  44. NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
  45. //获取cell的大小
  46. CGSize size = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
  47. CGFloat maxX = xOffset + size.width;
  48. if (maxX > collectionViewWidth - _sectionInsets.right) {
  49. xOffset = _sectionInsets.left;
  50. yOffset += size.height + _lineSpacing;
  51. }
  52. //创建一个item的attribute对象
  53. UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
  54. //当前cell坐标
  55. attributes.frame = CGRectMake(xOffset, yOffset, size.width, size.height);
  56. //保存cell信息
  57. [self.itemAttributes addObject:attributes];
  58. xOffset += size.width + _interitemSpacing;
  59. //内容总高度
  60. _contentSize.height = yOffset + size.height + _sectionInsets.bottom;
  61. }
  62. _contentSize.width = collectionViewWidth;
  63. }
  64. //返回指定范围的cell的布局的详细信息
  65. - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
  66. {
  67. return self.itemAttributes;
  68. }
  69. //返回指定cell的详细布局信息
  70. - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
  71. {
  72. return self.itemAttributes[indexPath.item];
  73. }
  74. //重新计算当前滚动视图的contentSize
  75. - (CGSize)collectionViewContentSize
  76. {
  77. return _contentSize;
  78. }
  79. @end