forked from steipete/PSTCollectionView
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSTCollectionView.m
More file actions
1135 lines (947 loc) · 48.9 KB
/
PSTCollectionView.m
File metadata and controls
1135 lines (947 loc) · 48.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// PSTCollectionView.m
// PSPDFKit
//
// Copyright (c) 2012 Peter Steinberger. All rights reserved.
//
#import "PSTCollectionView.h"
#import "PSTCollectionViewController.h"
#import "PSTCollectionViewData.h"
#import "PSTCollectionViewCell.h"
#import "PSTCollectionViewLayout.h"
#import "PSTCollectionViewFlowLayout.h"
#import "PSTCollectionViewItemKey.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>
@interface PSTCollectionViewLayout (Internal)
@property (nonatomic, unsafe_unretained) PSTCollectionView *collectionView;
@end
CGFloat PSTSimulatorAnimationDragCoefficient(void);
@class PSTCollectionViewExt;
@interface PSTCollectionView() {
// ivar layout needs to EQUAL to UICollectionView.
PSTCollectionViewLayout *_layout;
__unsafe_unretained id<PSTCollectionViewDataSource> _dataSource;
UIView *_backgroundView;
NSMutableSet *_indexPathsForSelectedItems;
NSMutableDictionary *_cellReuseQueues;
NSMutableDictionary *_supplementaryViewReuseQueues;
NSMutableSet *_indexPathsForHighlightedItems;
int _reloadingSuspendedCount;
PSTCollectionReusableView *_firstResponderView;
UIView *_newContentView;
int _firstResponderViewType;
NSString *_firstResponderViewKind;
NSIndexPath *_firstResponderIndexPath;
NSMutableDictionary *_allVisibleViewsDict;
NSIndexPath *_pendingSelectionIndexPath;
NSMutableSet *_pendingDeselectionIndexPaths;
PSTCollectionViewData *_collectionViewData;
id _update;
CGRect _visibleBounds;
CGRect _preRotationBounds;
CGPoint _rotationBoundsOffset;
int _rotationAnimationCount;
int _updateCount;
NSMutableArray *_insertItems;
NSMutableArray *_deleteItems;
NSMutableArray *_reloadItems;
NSMutableArray *_moveItems;
NSArray *_originalInsertItems;
NSArray *_originalDeleteItems;
UITouch *_currentTouch;
id _updateCompletionHandler;
NSMutableDictionary *_cellClassDict;
NSMutableDictionary *_cellNibDict;
NSMutableDictionary *_supplementaryViewClassDict;
NSMutableDictionary *_supplementaryViewNibDict;
NSMutableDictionary *_cellNibExternalObjectsTables;
NSMutableDictionary *_supplementaryViewNibExternalObjectsTables;
struct {
unsigned int delegateShouldHighlightItemAtIndexPath : 1;
unsigned int delegateDidHighlightItemAtIndexPath : 1;
unsigned int delegateDidUnhighlightItemAtIndexPath : 1;
unsigned int delegateShouldSelectItemAtIndexPath : 1;
unsigned int delegateShouldDeselectItemAtIndexPath : 1;
unsigned int delegateDidSelectItemAtIndexPath : 1;
unsigned int delegateDidDeselectItemAtIndexPath : 1;
unsigned int delegateSupportsMenus : 1;
unsigned int delegateDidEndDisplayingCell : 1;
unsigned int delegateDidEndDisplayingSupplementaryView : 1;
unsigned int dataSourceNumberOfSections : 1;
unsigned int dataSourceViewForSupplementaryElement : 1;
unsigned int reloadSkippedDuringSuspension : 1;
unsigned int scheduledUpdateVisibleCells : 1;
unsigned int scheduledUpdateVisibleCellLayoutAttributes : 1;
unsigned int allowsSelection : 1;
unsigned int allowsMultipleSelection : 1;
unsigned int updating : 1;
unsigned int fadeCellsForBoundsChange : 1;
unsigned int updatingLayout : 1;
unsigned int needsReload : 1;
unsigned int reloading : 1;
unsigned int skipLayoutDuringSnapshotting : 1;
unsigned int layoutInvalidatedSinceLastCellUpdate : 1;
unsigned int doneFirstLayout : 1;
} _collectionViewFlags;
CGPoint _lastLayoutOffset;
}
@property (nonatomic, strong) PSTCollectionViewData *collectionViewData;
@property (nonatomic, strong, readonly) PSTCollectionViewExt *extVars;
@end
// Used by PSTCollectionView for external variables.
// (We need to keep the total class size equal to the UICollectionView variant)
@interface PSTCollectionViewExt : NSObject
@property (nonatomic, strong) id nibObserverToken;
@property (nonatomic, strong) PSTCollectionViewLayout *nibLayout;
@property (nonatomic, strong) NSDictionary *nibCellsExternalObjects;
@property (nonatomic, strong) NSDictionary *supplementaryViewsExternalObjects;
@property (nonatomic, strong) NSIndexPath *touchingIndexPath;
@end
@implementation PSTCollectionViewExt @end
const char kPSTColletionViewExt;
@implementation PSTCollectionView
@synthesize collectionViewLayout = _layout;
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - NSObject
static void PSTCollectionViewCommonSetup(PSTCollectionView *_self) {
_self.allowsSelection = YES;
_self->_indexPathsForSelectedItems = [NSMutableSet new];
_self->_indexPathsForHighlightedItems = [NSMutableSet new];
_self->_cellReuseQueues = [NSMutableDictionary new];
_self->_supplementaryViewReuseQueues = [NSMutableDictionary new];
_self->_allVisibleViewsDict = [NSMutableDictionary new];
_self->_cellClassDict = [NSMutableDictionary new];
_self->_cellNibDict = [NSMutableDictionary new];
_self->_supplementaryViewClassDict = [NSMutableDictionary new];
_self->_supplementaryViewNibDict = [NSMutableDictionary new];
// add class that saves additional ivars
objc_setAssociatedObject(_self, &kPSTColletionViewExt, [PSTCollectionViewExt new], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id)initWithFrame:(CGRect)frame collectionViewLayout:(PSTCollectionViewLayout *)layout {
if ((self = [super initWithFrame:frame])) {
PSTCollectionViewCommonSetup(self);
self.collectionViewLayout = layout;
_collectionViewData = [[PSTCollectionViewData alloc] initWithCollectionView:self layout:layout];
}
return self;
}
- (id)initWithCoder:(NSCoder *)inCoder {
if ((self = [super initWithCoder:inCoder])) {
PSTCollectionViewCommonSetup(self);
// add observer for nib deserialization.
id nibObserverToken = [[NSNotificationCenter defaultCenter] addObserverForName:PSTCollectionViewLayoutAwokeFromNib object:nil queue:nil usingBlock:^(NSNotification *note) {
self.extVars.nibLayout = note.object;
}];
self.extVars.nibObserverToken = nibObserverToken;
NSDictionary *cellExternalObjects = [inCoder decodeObjectForKey:@"UICollectionViewCellPrototypeNibExternalObjects"];
NSDictionary *cellNibs = [inCoder decodeObjectForKey:@"UICollectionViewCellNibDict"];
for (NSString *identifier in cellNibs.allKeys) {
_cellNibDict[identifier] = cellNibs[identifier];
}
self.extVars.nibCellsExternalObjects = cellExternalObjects;
NSDictionary *supplementaryViewExternalObjects = [inCoder decodeObjectForKey:@"UICollectionViewSupplementaryViewPrototypeNibExternalObjects"];
NSDictionary *supplementaryViewNibs = [inCoder decodeObjectForKey:@"UICollectionViewSupplementaryViewNibDict"];
for (NSString *identifier in supplementaryViewNibs.allKeys) {
_supplementaryViewNibDict[identifier] = supplementaryViewNibs[identifier];
}
self.extVars.supplementaryViewsExternalObjects = supplementaryViewExternalObjects;
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
// check if NIB deserialization found a layout.
id nibObserverToken = self.extVars.nibObserverToken;
if (nibObserverToken) {
[[NSNotificationCenter defaultCenter] removeObserver:nibObserverToken];
self.extVars.nibObserverToken = nil;
}
PSTCollectionViewLayout *nibLayout = self.extVars.nibLayout;
if (nibLayout) {
self.collectionViewLayout = nibLayout;
self.extVars.nibLayout = nil;
}
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@ collection view layout: %@", [super description], self.collectionViewLayout];
}
- (void)dealloc {
id nibObserverToken = self.extVars.nibObserverToken;
if (nibObserverToken) [[NSNotificationCenter defaultCenter] removeObserver:nibObserverToken];
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - UIView
- (void)layoutSubviews {
[super layoutSubviews];
// Adding alpha animation to make the relayouting smooth
if (_collectionViewFlags.fadeCellsForBoundsChange) {
CATransition *transition = [CATransition animation];
transition.duration = 0.25f * PSTSimulatorAnimationDragCoefficient();
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[self.layer addAnimation:transition forKey:@"rotationAnimation"];
}
[_collectionViewData validateLayoutInRect:self.bounds];
// update cells
if (_collectionViewFlags.fadeCellsForBoundsChange) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
}
[self updateVisibleCellsNow:YES];
if (_collectionViewFlags.fadeCellsForBoundsChange) {
[CATransaction commit];
}
// do we need to update contentSize?
CGSize contentSize = [_collectionViewData collectionViewContentRect].size;
if (!CGSizeEqualToSize(self.contentSize, contentSize)) {
self.contentSize = contentSize;
// if contentSize is different, we need to re-evaluate layout, bounds (contentOffset) might changed
[_collectionViewData validateLayoutInRect:self.bounds];
[self updateVisibleCellsNow:YES];
}
_backgroundView.frame = (CGRect){.size=self.bounds.size};
_collectionViewFlags.fadeCellsForBoundsChange = NO;
}
- (void)setFrame:(CGRect)frame {
if (!CGRectEqualToRect(frame, self.frame)) {
if ([self.collectionViewLayout shouldInvalidateLayoutForBoundsChange:frame]) {
[self invalidateLayout];
_collectionViewFlags.fadeCellsForBoundsChange = YES;
}
[super setFrame:frame];
}
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Public
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
NSParameterAssert(cellClass);
NSParameterAssert(identifier);
_cellClassDict[identifier] = cellClass;
}
- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier {
NSParameterAssert(viewClass);
NSParameterAssert(elementKind);
NSParameterAssert(identifier);
NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", elementKind, identifier];
_supplementaryViewClassDict[kindAndIdentifier] = viewClass;
}
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier {
NSArray *topLevelObjects = [nib instantiateWithOwner:nil options:nil];
#pragma unused(topLevelObjects)
NSAssert(topLevelObjects.count == 1 && [topLevelObjects[0] isKindOfClass:PSTCollectionViewCell.class], @"must contain exactly 1 top level object which is a PSTCollectionViewCell");
_cellNibDict[identifier] = nib;
}
- (void)registerNib:(UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier {
NSArray *topLevelObjects = [nib instantiateWithOwner:nil options:nil];
#pragma unused(topLevelObjects)
NSAssert(topLevelObjects.count == 1 && [topLevelObjects[0] isKindOfClass:PSTCollectionReusableView.class], @"must contain exactly 1 top level object which is a PSTCollectionReusableView");
NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", kind, identifier];
_supplementaryViewNibDict[kindAndIdentifier] = nib;
}
- (id)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
// dequeue cell (if available)
NSMutableArray *reusableCells = _cellReuseQueues[identifier];
PSTCollectionViewCell *cell = [reusableCells lastObject];
if (cell) {
[reusableCells removeObjectAtIndex:[reusableCells count]-1];
}else {
if (_cellNibDict[identifier]) {
// Cell was registered via registerNib:forCellWithReuseIdentifier:
UINib *cellNib = _cellNibDict[identifier];
NSDictionary *externalObjects = self.extVars.nibCellsExternalObjects[identifier];
if (externalObjects) {
cell = [cellNib instantiateWithOwner:self options:@{UINibExternalObjects:externalObjects}][0];
} else {
cell = [cellNib instantiateWithOwner:self options:0][0];
}
} else {
Class cellClass = _cellClassDict[identifier];
// compatiblity layer
Class collectionViewCellClass = NSClassFromString(@"UICollectionViewCell");
if (collectionViewCellClass && [cellClass isEqual:collectionViewCellClass]) {
cellClass = [PSTCollectionViewCell class];
}
if (cellClass == nil) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"Class not registered for identifier %@", identifier] userInfo:nil];
}
if (self.collectionViewLayout) {
PSTCollectionViewLayoutAttributes *attributes = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
cell = [[cellClass alloc] initWithFrame:attributes.frame];
} else {
cell = [cellClass new];
}
}
cell.collectionView = self;
cell.reuseIdentifier = identifier;
}
return cell;
}
- (id)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", elementKind, identifier];
NSMutableArray *reusableViews = _supplementaryViewReuseQueues[kindAndIdentifier];
PSTCollectionReusableView *view = [reusableViews lastObject];
if (view) {
[reusableViews removeObjectAtIndex:reusableViews.count - 1];
} else {
if (_supplementaryViewNibDict[kindAndIdentifier]) {
// supplementary view was registered via registerNib:forCellWithReuseIdentifier:
UINib *supplementaryViewNib = _supplementaryViewNibDict[kindAndIdentifier];
NSDictionary *externalObjects = self.extVars.supplementaryViewsExternalObjects[kindAndIdentifier];
if (externalObjects) {
view = [supplementaryViewNib instantiateWithOwner:self options:@{UINibExternalObjects:externalObjects}][0];
} else {
view = [supplementaryViewNib instantiateWithOwner:self options:0][0];
}
} else {
Class viewClass = _supplementaryViewClassDict[kindAndIdentifier];
Class reusableViewClass = NSClassFromString(@"UICollectionReusableView");
if (reusableViewClass && [viewClass isEqual:reusableViewClass]) {
viewClass = [PSTCollectionReusableView class];
}
if (viewClass == nil) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"Class not registered for kind/identifier %@", kindAndIdentifier] userInfo:nil];
}
if (self.collectionViewLayout) {
PSTCollectionViewLayoutAttributes *attributes = [self.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:elementKind
atIndexPath:indexPath];
view = [[viewClass alloc] initWithFrame:attributes.frame];
} else {
view = [viewClass new];
}
}
view.collectionView = self;
view.reuseIdentifier = identifier;
}
return view;
}
- (NSArray *)visibleCells {
return [[_allVisibleViewsDict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject isKindOfClass:[PSTCollectionViewCell class]];
}]];
}
- (void)reloadData {
if (_reloadingSuspendedCount != 0) return;
[self invalidateLayout];
[_allVisibleViewsDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[UIView class]]) {
[obj removeFromSuperview];
}
}];
[_allVisibleViewsDict removeAllObjects];
for(NSIndexPath *indexPath in _indexPathsForSelectedItems) {
PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:indexPath];
selectedCell.selected = NO;
selectedCell.highlighted = NO;
}
[_indexPathsForSelectedItems removeAllObjects];
[_indexPathsForHighlightedItems removeAllObjects];
[self setNeedsLayout];
//NSAssert(sectionCount == 1, @"Sections are currently not supported.");
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Query Grid
- (NSInteger)numberOfSections {
return [_collectionViewData numberOfSections];
}
- (NSInteger)numberOfItemsInSection:(NSInteger)section {
return [_collectionViewData numberOfItemsInSection:section];
}
- (PSTCollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
return [[self collectionViewLayout] layoutAttributesForItemAtIndexPath:indexPath];
}
- (PSTCollectionViewLayoutAttributes *)layoutAttributesForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
return [[self collectionViewLayout] layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
}
- (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point {
__block NSIndexPath *indexPath = nil;
[_allVisibleViewsDict enumerateKeysAndObjectsWithOptions:kNilOptions usingBlock:^(id key, id obj, BOOL *stop) {
PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
if (itemKey.type == PSTCollectionViewItemTypeCell) {
PSTCollectionViewCell *cell = (PSTCollectionViewCell *)obj;
if (CGRectContainsPoint(cell.frame, point)) {
indexPath = itemKey.indexPath;
*stop = YES;
}
}
}];
return indexPath;
}
- (NSIndexPath *)indexPathForCell:(PSTCollectionViewCell *)cell {
__block NSIndexPath *indexPath = nil;
[_allVisibleViewsDict enumerateKeysAndObjectsWithOptions:kNilOptions usingBlock:^(id key, id obj, BOOL *stop) {
PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
if (itemKey.type == PSTCollectionViewItemTypeCell) {
PSTCollectionViewCell *currentCell = (PSTCollectionViewCell *)obj;
if (currentCell == cell) {
indexPath = itemKey.indexPath;
*stop = YES;
}
}
}];
return indexPath;
}
- (PSTCollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath {
// NSInteger index = [_collectionViewData globalIndexForItemAtIndexPath:indexPath];
// TODO Apple uses some kind of globalIndex for this.
__block PSTCollectionViewCell *cell = nil;
[_allVisibleViewsDict enumerateKeysAndObjectsWithOptions:0 usingBlock:^(id key, id obj, BOOL *stop) {
PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
if (itemKey.type == PSTCollectionViewItemTypeCell) {
if ([itemKey.indexPath isEqual:indexPath]) {
cell = obj;
*stop = YES;
}
}
}];
return cell;
}
- (NSArray *)indexPathsForVisibleItems {
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:[_allVisibleViewsDict count]];
[_allVisibleViewsDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
if (itemKey.type == PSTCollectionViewItemTypeCell) {
[indexPaths addObject:itemKey.indexPath];
}
}];
return indexPaths;
}
// returns nil or an array of selected index paths
- (NSArray *)indexPathsForSelectedItems {
return [_indexPathsForSelectedItems allObjects];
}
// Interacting with the collection view.
- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(PSTCollectionViewScrollPosition)scrollPosition animated:(BOOL)animated {
// ensure grid is layouted; else we can't scroll.
[self layoutSubviews];
PSTCollectionViewLayoutAttributes *layoutAttributes = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
if (layoutAttributes) {
CGRect targetRect = layoutAttributes.frame;
// hack to add proper margins to flowlayout.
// TODO: how to pack this into PSTCollectionViewFlowLayout?
if ([self.collectionViewLayout isKindOfClass:[PSTCollectionViewFlowLayout class]]) {
PSTCollectionViewFlowLayout *flowLayout = (PSTCollectionViewFlowLayout *)self.collectionViewLayout;
targetRect.size.height += flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical ? flowLayout.minimumLineSpacing : flowLayout.minimumInteritemSpacing;
targetRect.size.width += flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing;
}
[self scrollRectToVisible:targetRect animated:animated];
}
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Touch Handling
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
CGPoint touchPoint = [[touches anyObject] locationInView:self];
NSIndexPath *indexPath = [self indexPathForItemAtPoint:touchPoint];
if (indexPath) {
if (!self.allowsMultipleSelection) {
// temporally unhighlight background on touchesBegan (keeps selected by _indexPathsForSelectedItems)
for (PSTCollectionViewCell* visibleCell in self.visibleCells) {
visibleCell.highlighted = NO;
visibleCell.selected = NO;
// NOTE: doesn't work due to the _indexPathsForHighlightedItems validation
//[self unhighlightItemAtIndexPath:indexPathForVisibleItem animated:YES notifyDelegate:YES];
}
}
[self highlightItemAtIndexPath:indexPath animated:YES scrollPosition:PSTCollectionViewScrollPositionNone notifyDelegate:YES];
self.extVars.touchingIndexPath = indexPath;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
if (self.extVars.touchingIndexPath) {
CGPoint touchPoint = [[touches anyObject] locationInView:self];
NSIndexPath *indexPath = [self indexPathForItemAtPoint:touchPoint];
if ([indexPath isEqual:self.extVars.touchingIndexPath]) {
[self highlightItemAtIndexPath:indexPath animated:YES scrollPosition:PSTCollectionViewScrollPositionNone notifyDelegate:YES];
}
else {
[self unhighlightItemAtIndexPath:self.extVars.touchingIndexPath animated:YES notifyDelegate:YES];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
CGPoint touchPoint = [[touches anyObject] locationInView:self];
NSIndexPath *indexPath = [self indexPathForItemAtPoint:touchPoint];
if ([indexPath isEqual:self.extVars.touchingIndexPath]) {
[self userSelectedItemAtIndexPath:indexPath];
[self unhighlightAllItems];
self.extVars.touchingIndexPath = nil;
}
else {
[self cellTouchCancelled];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self cellTouchCancelled];
}
- (void)cellTouchCancelled {
// TODO: improve behavior on touchesCancelled
if (!self.allowsMultipleSelection) {
// highlight selected-background again
for (PSTCollectionViewCell* visibleCell in self.visibleCells) {
NSIndexPath* indexPathForVisibleItem = [self indexPathForCell:visibleCell];
visibleCell.selected = [_indexPathsForSelectedItems containsObject:indexPathForVisibleItem];
}
}
[self unhighlightAllItems];
self.extVars.touchingIndexPath = nil;
}
- (void)userSelectedItemAtIndexPath:(NSIndexPath *)indexPath {
if (self.allowsMultipleSelection && [_indexPathsForSelectedItems containsObject:indexPath]) {
[self deselectItemAtIndexPath:indexPath animated:YES notifyDelegate:YES];
}
else {
[self selectItemAtIndexPath:indexPath animated:YES scrollPosition:PSTCollectionViewScrollPositionNone notifyDelegate:YES];
}
}
// select item, notify delegate (internal)
- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(PSTCollectionViewScrollPosition)scrollPosition notifyDelegate:(BOOL)notifyDelegate {
BOOL shouldSelect = YES;
if (notifyDelegate && _collectionViewFlags.delegateShouldSelectItemAtIndexPath) {
shouldSelect = [self.delegate collectionView:self shouldSelectItemAtIndexPath:indexPath];
}
if (shouldSelect) {
if (!self.allowsMultipleSelection) {
for (NSIndexPath *selectedIndexPath in [_indexPathsForSelectedItems copy]) {
if(![indexPath isEqual:selectedIndexPath]) {
[self deselectItemAtIndexPath:selectedIndexPath animated:animated notifyDelegate:notifyDelegate];
}
}
}
if (self.allowsSelection) {
PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:indexPath];
selectedCell.selected = YES;
[_indexPathsForSelectedItems addObject:indexPath];
}
// call delegate
if (notifyDelegate && _collectionViewFlags.delegateDidSelectItemAtIndexPath) {
[self.delegate collectionView:self didSelectItemAtIndexPath:indexPath];
}
}
[self unhighlightItemAtIndexPath:indexPath animated:animated notifyDelegate:YES];
}
- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(PSTCollectionViewScrollPosition)scrollPosition {
[self selectItemAtIndexPath:indexPath animated:animated scrollPosition:scrollPosition notifyDelegate:NO];
}
- (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated
{
[self deselectItemAtIndexPath:indexPath animated:animated notifyDelegate:NO];
}
- (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated notifyDelegate:(BOOL)notify {
if ([_indexPathsForSelectedItems containsObject:indexPath]) {
PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:indexPath];
selectedCell.selected = NO;
[_indexPathsForSelectedItems removeObject:indexPath];
[self unhighlightItemAtIndexPath:indexPath animated:animated notifyDelegate:notify];
if (notify && _collectionViewFlags.delegateDidDeselectItemAtIndexPath) {
[self.delegate collectionView:self didDeselectItemAtIndexPath:indexPath];
}
}
}
- (BOOL)highlightItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(PSTCollectionViewScrollPosition)scrollPosition notifyDelegate:(BOOL)notifyDelegate {
BOOL shouldHighlight = YES;
if (notifyDelegate && _collectionViewFlags.delegateShouldHighlightItemAtIndexPath) {
shouldHighlight = [self.delegate collectionView:self shouldHighlightItemAtIndexPath:indexPath];
}
if (shouldHighlight) {
PSTCollectionViewCell *highlightedCell = [self cellForItemAtIndexPath:indexPath];
highlightedCell.highlighted = YES;
[_indexPathsForHighlightedItems addObject:indexPath];
if (notifyDelegate && _collectionViewFlags.delegateDidHighlightItemAtIndexPath) {
[self.delegate collectionView:self didHighlightItemAtIndexPath:indexPath];
}
}
return shouldHighlight;
}
- (void)unhighlightItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated notifyDelegate:(BOOL)notifyDelegate {
if ([_indexPathsForHighlightedItems containsObject:indexPath]) {
PSTCollectionViewCell *highlightedCell = [self cellForItemAtIndexPath:indexPath];
highlightedCell.highlighted = NO;
[_indexPathsForHighlightedItems removeObject:indexPath];
if (notifyDelegate && _collectionViewFlags.delegateDidUnhighlightItemAtIndexPath) {
[self.delegate collectionView:self didUnhighlightItemAtIndexPath:indexPath];
}
}
}
- (void)unhighlightAllItems {
for (NSIndexPath *indexPath in [_indexPathsForHighlightedItems copy]) {
[self unhighlightItemAtIndexPath:indexPath animated:NO notifyDelegate:YES];
}
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Update Grid
- (void)insertSections:(NSIndexSet *)sections {
[self reloadData];
}
- (void)deleteSections:(NSIndexSet *)sections {
[self reloadData];
}
- (void)reloadSections:(NSIndexSet *)sections {
[self reloadData];
}
- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection {
[self reloadData];
}
- (void)insertItemsAtIndexPaths:(NSArray *)indexPaths {
[self reloadData];
}
- (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths {
[self reloadData];
}
- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths {
// check to see if reload should hold off
if (_reloadingSuspendedCount != 0 && _collectionViewFlags.reloadSkippedDuringSuspension) {
[_reloadItems addObjectsFromArray:indexPaths];
_collectionViewFlags.needsReload = YES;
return;
}
_collectionViewFlags.reloading = YES;
NSSet *visibleCellKeys = [_allVisibleViewsDict keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
if (itemKey.type == PSTCollectionViewItemTypeCell && [indexPaths containsObject:itemKey.indexPath]) {
return YES;
}
return NO;
}];
for (PSTCollectionViewItemKey *itemKey in visibleCellKeys) {
PSTCollectionViewCell *reusableView = (PSTCollectionViewCell *)[_allVisibleViewsDict objectForKey:itemKey];
//Remove the old cell
[reusableView removeFromSuperview];
[_allVisibleViewsDict removeObjectForKey:itemKey];
if ([self.delegate respondsToSelector:@selector(collectionView:didEndDisplayingCell:forItemAtIndexPath:)]) {
[self.delegate collectionView:self didEndDisplayingCell:(PSTCollectionViewCell *)reusableView forItemAtIndexPath:itemKey.indexPath];
}
[self reuseCell:(PSTCollectionViewCell *)reusableView];
//Reload the cell and redisplay
PSTCollectionViewLayoutAttributes *layoutAttributes = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:itemKey.indexPath];
PSTCollectionViewCell *newCell = [self createPreparedCellForItemAtIndexPath:itemKey.indexPath withLayoutAttributes:layoutAttributes];
newCell.selected = NO;
newCell.highlighted = NO;
_allVisibleViewsDict[itemKey] = newCell;
[self addControlledSubview:newCell];
}
for(NSIndexPath *indexPath in indexPaths) {
[_indexPathsForHighlightedItems removeObject:indexPath];
[_indexPathsForSelectedItems removeObject:indexPath];
}
_collectionViewFlags.reloading = NO;
}
- (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath {
[self reloadData];
}
- (void)performBatchUpdates:(void (^)(void))updates completion:(void (^)(BOOL finished))completion {
if (updates) {
updates();
}
if (completion) {
completion(YES);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Properties
- (void)setBackgroundView:(UIView *)backgroundView {
if (backgroundView != _backgroundView) {
[_backgroundView removeFromSuperview];
_backgroundView = backgroundView;
[self.superview addSubview:_backgroundView];
[self.superview sendSubviewToBack:_backgroundView];
}
}
- (void)setCollectionViewLayout:(PSTCollectionViewLayout *)layout animated:(BOOL)animated {
if (layout != _layout) {
_layout.collectionView = nil;
_layout = layout;
layout.collectionView = self;
_collectionViewData = [[PSTCollectionViewData alloc] initWithCollectionView:self layout:layout];
[self reloadData];
}
}
- (void)setCollectionViewLayout:(PSTCollectionViewLayout *)layout {
[self setCollectionViewLayout:layout animated:NO];
}
- (void)setDelegate:(id<PSTCollectionViewDelegate>)delegate {
super.delegate = delegate;
// Managing the Selected Cells
_collectionViewFlags.delegateShouldSelectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:shouldSelectItemAtIndexPath:)];
_collectionViewFlags.delegateDidSelectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)];
_collectionViewFlags.delegateShouldDeselectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:shouldDeselectItemAtIndexPath:)];
_collectionViewFlags.delegateDidDeselectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didDeselectItemAtIndexPath:)];
// Managing Cell Highlighting
_collectionViewFlags.delegateShouldHighlightItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:shouldHighlightItemAtIndexPath:)];
_collectionViewFlags.delegateDidHighlightItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didHighlightItemAtIndexPath:)];
_collectionViewFlags.delegateDidUnhighlightItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didUnhighlightItemAtIndexPath:)];
// Tracking the Removal of Views
_collectionViewFlags.delegateDidEndDisplayingCell = [self.delegate respondsToSelector:@selector(collectionView:didEndDisplayingCell:forItemAtIndexPath:)];
_collectionViewFlags.delegateDidEndDisplayingSupplementaryView = [self.delegate respondsToSelector:@selector(collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:)];
// Managing Actions for Cells
_collectionViewFlags.delegateSupportsMenus = [self.delegate respondsToSelector:@selector(collectionView:shouldShowMenuForItemAtIndexPath:)];
// These aren't present in the flags which is a little strange. Not adding them because thet will mess with byte alignment which will affect cross compatibility.
// The flag names are guesses and are there for documentation purposes.
//
// _collectionViewFlags.delegateCanPerformActionForItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:canPerformAction:forItemAtIndexPath:withSender:)];
// _collectionViewFlags.delegatePerformActionForItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:performAction:forItemAtIndexPath:withSender:)];
}
// Might be overkill since two are required and two are handled by PSTCollectionViewData leaving only one flag we actually need to check for
- (void)setDataSource:(id<PSTCollectionViewDataSource>)dataSource {
if (dataSource != _dataSource) {
_dataSource = dataSource;
// Getting Item and Section Metrics
_collectionViewFlags.dataSourceNumberOfSections = [_dataSource respondsToSelector:@selector(numberOfSectionsInCollectionView:)];
// Getting Views for Items
_collectionViewFlags.dataSourceViewForSupplementaryElement = [_dataSource respondsToSelector:@selector(collectionView:viewForSupplementaryElementOfKind:atIndexPath:)];
}
}
- (BOOL)allowsSelection {
return _collectionViewFlags.allowsSelection;
}
- (void)setAllowsSelection:(BOOL)allowsSelection {
_collectionViewFlags.allowsSelection = allowsSelection;
}
- (BOOL)allowsMultipleSelection {
return _collectionViewFlags.allowsMultipleSelection;
}
- (void)setAllowsMultipleSelection:(BOOL)allowsMultipleSelection {
_collectionViewFlags.allowsMultipleSelection = allowsMultipleSelection;
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private
- (PSTCollectionViewExt *)extVars {
return objc_getAssociatedObject(self, &kPSTColletionViewExt);
}
- (void)invalidateLayout {
[self.collectionViewLayout invalidateLayout];
[self.collectionViewData invalidate]; // invalidate layout cache
}
// update currently visible cells, fetches new cells if needed
// TODO: use now parameter.
- (void)updateVisibleCellsNow:(BOOL)now {
NSArray *layoutAttributesArray = [_collectionViewData layoutAttributesForElementsInRect:self.bounds];
// create ItemKey/Attributes dictionary
NSMutableDictionary *itemKeysToAddDict = [NSMutableDictionary dictionary];
for (PSTCollectionViewLayoutAttributes *layoutAttributes in layoutAttributesArray) {
PSTCollectionViewItemKey *itemKey = [PSTCollectionViewItemKey collectionItemKeyForLayoutAttributes:layoutAttributes];
itemKeysToAddDict[itemKey] = layoutAttributes;
}
// detect what items should be removed and queued back.
NSMutableSet *allVisibleItemKeys = [NSMutableSet setWithArray:[_allVisibleViewsDict allKeys]];
[allVisibleItemKeys minusSet:[NSSet setWithArray:[itemKeysToAddDict allKeys]]];
// remove views that have not been processed and prepare them for re-use.
for (PSTCollectionViewItemKey *itemKey in allVisibleItemKeys) {
PSTCollectionReusableView *reusableView = _allVisibleViewsDict[itemKey];
if (reusableView) {
[reusableView removeFromSuperview];
[_allVisibleViewsDict removeObjectForKey:itemKey];
if (itemKey.type == PSTCollectionViewItemTypeCell) {
if (_collectionViewFlags.delegateDidEndDisplayingCell) {
[self.delegate collectionView:self didEndDisplayingCell:(PSTCollectionViewCell *)reusableView forItemAtIndexPath:itemKey.indexPath];
}
[self reuseCell:(PSTCollectionViewCell *)reusableView];
}else if(itemKey.type == PSTCollectionViewItemTypeSupplementaryView) {
if (_collectionViewFlags.delegateDidEndDisplayingSupplementaryView) {
[self.delegate collectionView:self didEndDisplayingSupplementaryView:reusableView forElementOfKind:itemKey.identifier atIndexPath:itemKey.indexPath];
}
[self reuseSupplementaryView:reusableView];
}
// TODO: decoration views etc?
}
}
// finally add new cells.
[itemKeysToAddDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
PSTCollectionViewItemKey *itemKey = key;
PSTCollectionViewLayoutAttributes *layoutAttributes = obj;
// check if cell is in visible dict; add it if not.
PSTCollectionReusableView *view = _allVisibleViewsDict[itemKey];
if (!view) {
if (itemKey.type == PSTCollectionViewItemTypeCell) {
view = [self createPreparedCellForItemAtIndexPath:itemKey.indexPath withLayoutAttributes:layoutAttributes];
} else if (itemKey.type == PSTCollectionViewItemTypeSupplementaryView) {
view = [self createPreparedSupplementaryViewForElementOfKind:layoutAttributes.representedElementKind
atIndexPath:layoutAttributes.indexPath
withLayoutAttributes:layoutAttributes];
}
//Supplementary views are optional
if (view) {
_allVisibleViewsDict[itemKey] = view;
[self addControlledSubview:view];
}
}else {
// just update cell
[view applyLayoutAttributes:layoutAttributes];
}
}];
}
// fetches a cell from the dataSource and sets the layoutAttributes
- (PSTCollectionViewCell *)createPreparedCellForItemAtIndexPath:(NSIndexPath *)indexPath withLayoutAttributes:(PSTCollectionViewLayoutAttributes *)layoutAttributes {
PSTCollectionViewCell *cell = [self.dataSource collectionView:self cellForItemAtIndexPath:indexPath];
// reset selected/highlight state
[cell setHighlighted:[_indexPathsForHighlightedItems containsObject:indexPath]];
[cell setSelected:[_indexPathsForSelectedItems containsObject:indexPath]];
// voiceover support
cell.isAccessibilityElement = YES;
[cell applyLayoutAttributes:layoutAttributes];
return cell;
}
- (PSTCollectionReusableView *)createPreparedSupplementaryViewForElementOfKind:(NSString *)kind
atIndexPath:(NSIndexPath *)indexPath
withLayoutAttributes:(PSTCollectionViewLayoutAttributes *)layoutAttributes
{
if (_collectionViewFlags.dataSourceViewForSupplementaryElement) {
PSTCollectionReusableView *view = [self.dataSource collectionView:self
viewForSupplementaryElementOfKind:kind
atIndexPath:indexPath];
[view applyLayoutAttributes:layoutAttributes];
return view;
}
return nil;
}
// @steipete optimization
- (void)queueReusableView:(PSTCollectionReusableView *)reusableView inQueue:(NSMutableDictionary *)queue {
NSString *cellIdentifier = reusableView.reuseIdentifier;
NSParameterAssert([cellIdentifier length]);
[reusableView removeFromSuperview];
[reusableView prepareForReuse];
// enqueue cell
NSMutableArray *reuseableViews = queue[cellIdentifier];
if (!reuseableViews) {
reuseableViews = [NSMutableArray array];
queue[cellIdentifier] = reuseableViews;
}
[reuseableViews addObject:reusableView];
}
// enqueue cell for reuse
- (void)reuseCell:(PSTCollectionViewCell *)cell {
[self queueReusableView:cell inQueue:_cellReuseQueues];
}
// enqueue supplementary view for reuse
- (void)reuseSupplementaryView:(PSTCollectionReusableView *)supplementaryView {
[self queueReusableView:supplementaryView inQueue:_supplementaryViewReuseQueues];
}
- (void)addControlledSubview:(PSTCollectionReusableView *)subview {
// avoids placing views above the scroll indicator
[self insertSubview:subview atIndex:0];
}
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - PSTCollection/UICollection interoperability
#import <objc/message.h>
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
NSMethodSignature *sig = [super methodSignatureForSelector:selector];
if(!sig) {