YBIBCollectionView.m 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // YBIBCollectionView.m
  3. // YBImageBrowserDemo
  4. //
  5. // Created by 波儿菜 on 2019/6/6.
  6. // Copyright © 2019 波儿菜. All rights reserved.
  7. //
  8. #import "YBIBCollectionView.h"
  9. @implementation YBIBCollectionView {
  10. NSMutableSet *_reuseSet;
  11. }
  12. #pragma mark - life cycle
  13. - (instancetype)initWithFrame:(CGRect)frame {
  14. _layout = [YBIBCollectionViewLayout new];
  15. return [self initWithFrame:frame collectionViewLayout:_layout];
  16. }
  17. - (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(nonnull UICollectionViewLayout *)layout {
  18. self = [super initWithFrame:frame collectionViewLayout:layout];
  19. if (self) {
  20. self.backgroundColor = [UIColor clearColor];
  21. self.pagingEnabled = YES;
  22. self.showsHorizontalScrollIndicator = NO;
  23. self.showsVerticalScrollIndicator = NO;
  24. self.alwaysBounceVertical = NO;
  25. self.alwaysBounceHorizontal = NO;
  26. self.decelerationRate = UIScrollViewDecelerationRateFast;
  27. if (@available(iOS 11.0, *)) {
  28. self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  29. }
  30. _reuseSet = [NSMutableSet set];
  31. }
  32. return self;
  33. }
  34. #pragma mark - public
  35. - (NSString *)reuseIdentifierForCellClass:(Class)cellClass {
  36. NSString *identifier = NSStringFromClass(cellClass);
  37. if (![_reuseSet containsObject:identifier]) {
  38. NSString *path = [[NSBundle mainBundle] pathForResource:identifier ofType:@"nib"];
  39. if (path) {
  40. [self registerNib:[UINib nibWithNibName:identifier bundle:nil] forCellWithReuseIdentifier:identifier];
  41. } else {
  42. [self registerClass:cellClass forCellWithReuseIdentifier:identifier];
  43. }
  44. [_reuseSet addObject:identifier];
  45. }
  46. return identifier;
  47. }
  48. - (UICollectionViewCell *)centerCell {
  49. NSArray<UICollectionViewCell *> *cells = [self visibleCells];
  50. if (cells.count == 0) return nil;
  51. UICollectionViewCell *res = cells[0];
  52. CGFloat centerX = self.contentOffset.x + (self.bounds.size.width / 2.0);
  53. for (int i = 1; i < cells.count; ++i) {
  54. if (ABS(cells[i].center.x - centerX) < ABS(res.center.x - centerX)) {
  55. res = cells[i];
  56. }
  57. }
  58. return res;
  59. }
  60. - (void)scrollToPage:(NSInteger)page {
  61. [self setContentOffset:CGPointMake(self.bounds.size.width * page, 0)];
  62. }
  63. #pragma mark - hit test
  64. - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
  65. UIView *view = [super hitTest:point withEvent:event];
  66. // When the hit-test view is 'UISlider', set '_scrollEnabled' to 'NO', avoid gesture conflicts.
  67. self.scrollEnabled = ![view isKindOfClass:UISlider.class];
  68. return view;
  69. }
  70. @end