财神随手记账

LineLayout.m 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // LineLayout.m
  3. // CollectionView-LineLayout
  4. //
  5. // Created by Kobe24 on 2018/1/2.
  6. // Copyright © 2018年 SYD. All rights reserved.
  7. //
  8. #import "LineLayout.h"
  9. #define ItemSize 150
  10. #define LineSpacing 50
  11. @implementation LineLayout
  12. - (instancetype)init{
  13. if (self = [super init]) {
  14. self.itemSize = CGSizeMake(ItemSize, ItemSize);
  15. self.minimumLineSpacing = LineSpacing;
  16. self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;//速率
  17. self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
  18. //水平方向
  19. }
  20. return self;
  21. }
  22. //返回滚动停止的点 自动对齐中心
  23. - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
  24. CGFloat offSetAdjustment = MAXFLOAT;
  25. //预期停止水平中心点
  26. CGFloat horizotalCenter = proposedContentOffset.x + self.collectionView.bounds.size.width / 2;
  27. //预期滚动停止时的屏幕区域
  28. CGRect targetRect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
  29. //找出最接近中心点的item
  30. NSArray *array = [super layoutAttributesForElementsInRect:targetRect];
  31. for (UICollectionViewLayoutAttributes * attributes in array) {
  32. CGFloat currentCenterX = attributes.center.x;
  33. if (ABS(currentCenterX - horizotalCenter) < ABS(offSetAdjustment)) {
  34. offSetAdjustment = currentCenterX - horizotalCenter;
  35. }
  36. }
  37. //
  38. return CGPointMake(proposedContentOffset.x + offSetAdjustment, proposedContentOffset.y);
  39. }
  40. - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
  41. NSArray *original = [super layoutAttributesForElementsInRect:rect];
  42. NSArray *array = [[NSArray alloc] initWithArray:original copyItems:YES];
  43. CGRect visibleRect;
  44. visibleRect.origin = self.collectionView.contentOffset;
  45. visibleRect.size = self.collectionView.bounds.size;
  46. for (UICollectionViewLayoutAttributes * attributes in array) {
  47. //判断相交
  48. if (CGRectIntersectsRect(visibleRect, rect)) {
  49. //当前视图中心点 距离item中心点距离
  50. CGFloat distance = CGRectGetMidX(self.collectionView.bounds) - attributes.center.x;
  51. CGFloat normalizedDistance = distance / 200;
  52. if (ABS(distance) < 200) {
  53. CGFloat zoom = 1 + 0.4 * (1 - ABS(normalizedDistance));
  54. attributes.transform3D = CATransform3DMakeScale(zoom, zoom, 1);
  55. attributes.zIndex = 1;
  56. }
  57. }
  58. }
  59. return array;
  60. }
  61. - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
  62. return YES;
  63. }
  64. @end