PSTCollectionView.m 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  1. //
  2. // PSTCollectionView.m
  3. // PSPDFKit
  4. //
  5. // Copyright (c) 2012-2013 Peter Steinberger. All rights reserved.
  6. //
  7. #import "PSTCollectionView.h"
  8. #import "PSTCollectionViewData.h"
  9. #import "PSTCollectionViewLayout+Internals.h"
  10. #import "PSTCollectionViewItemKey.h"
  11. #import <objc/runtime.h>
  12. #import <dlfcn.h>
  13. @interface PSTCollectionViewLayout (Internal)
  14. @property (nonatomic, unsafe_unretained) PSTCollectionView *collectionView;
  15. @end
  16. @interface PSTCollectionViewData (Internal)
  17. - (void)prepareToLoadData;
  18. @end
  19. @interface PSTCollectionViewCell (Internal)
  20. - (void)performSelectionSegue;
  21. @end
  22. @interface PSTCollectionViewUpdateItem ()
  23. - (NSIndexPath *)indexPath;
  24. - (BOOL)isSectionOperation;
  25. @end
  26. @interface PSTCollectionViewLayoutAttributes () {
  27. char junk[128];
  28. }
  29. @property (nonatomic, copy) NSString *elementKind;
  30. @end
  31. CGFloat PSTSimulatorAnimationDragCoefficient(void);
  32. @class PSTCollectionViewExt;
  33. @interface PSTCollectionView () <UIScrollViewDelegate> {
  34. // ivar layout needs to EQUAL to UICollectionView.
  35. PSTCollectionViewLayout *_layout;
  36. __unsafe_unretained id<PSTCollectionViewDataSource> _dataSource;
  37. UIView *_backgroundView;
  38. NSMutableSet *_indexPathsForSelectedItems;
  39. NSMutableDictionary *_cellReuseQueues;
  40. NSMutableDictionary *_supplementaryViewReuseQueues;
  41. NSMutableDictionary *_decorationViewReuseQueues;
  42. NSMutableSet *_indexPathsForHighlightedItems;
  43. int _reloadingSuspendedCount;
  44. PSTCollectionReusableView *_firstResponderView;
  45. UIView *_newContentView;
  46. int _firstResponderViewType;
  47. NSString *_firstResponderViewKind;
  48. NSIndexPath *_firstResponderIndexPath;
  49. NSMutableDictionary *_allVisibleViewsDict;
  50. NSIndexPath *_pendingSelectionIndexPath;
  51. NSMutableSet *_pendingDeselectionIndexPaths;
  52. PSTCollectionViewData *_collectionViewData;
  53. id _update;
  54. CGRect _visibleBoundRects;
  55. CGRect _preRotationBounds;
  56. CGPoint _rotationBoundsOffset;
  57. int _rotationAnimationCount;
  58. int _updateCount;
  59. NSMutableArray *_insertItems;
  60. NSMutableArray *_deleteItems;
  61. NSMutableArray *_reloadItems;
  62. NSMutableArray *_moveItems;
  63. NSArray *_originalInsertItems;
  64. NSArray *_originalDeleteItems;
  65. UITouch *_currentTouch;
  66. void (^_updateCompletionHandler)(BOOL finished);
  67. NSMutableDictionary *_cellClassDict;
  68. NSMutableDictionary *_cellNibDict;
  69. NSMutableDictionary *_supplementaryViewClassDict;
  70. NSMutableDictionary *_supplementaryViewNibDict;
  71. NSMutableDictionary *_cellNibExternalObjectsTables;
  72. NSMutableDictionary *_supplementaryViewNibExternalObjectsTables;
  73. struct {
  74. unsigned int delegateShouldHighlightItemAtIndexPath : 1;
  75. unsigned int delegateDidHighlightItemAtIndexPath : 1;
  76. unsigned int delegateDidUnhighlightItemAtIndexPath : 1;
  77. unsigned int delegateShouldSelectItemAtIndexPath : 1;
  78. unsigned int delegateShouldDeselectItemAtIndexPath : 1;
  79. unsigned int delegateDidSelectItemAtIndexPath : 1;
  80. unsigned int delegateDidDeselectItemAtIndexPath : 1;
  81. unsigned int delegateSupportsMenus : 1;
  82. unsigned int delegateDidEndDisplayingCell : 1;
  83. unsigned int delegateDidEndDisplayingSupplementaryView : 1;
  84. unsigned int dataSourceNumberOfSections : 1;
  85. unsigned int dataSourceViewForSupplementaryElement : 1;
  86. unsigned int reloadSkippedDuringSuspension : 1;
  87. unsigned int scheduledUpdateVisibleCells : 1;
  88. unsigned int scheduledUpdateVisibleCellLayoutAttributes : 1;
  89. unsigned int allowsSelection : 1;
  90. unsigned int allowsMultipleSelection : 1;
  91. unsigned int updating : 1;
  92. unsigned int fadeCellsForBoundsChange : 1;
  93. unsigned int updatingLayout : 1;
  94. unsigned int needsReload : 1;
  95. unsigned int reloading : 1;
  96. unsigned int skipLayoutDuringSnapshotting : 1;
  97. unsigned int layoutInvalidatedSinceLastCellUpdate : 1;
  98. unsigned int doneFirstLayout : 1;
  99. }_collectionViewFlags;
  100. CGPoint _lastLayoutOffset;
  101. char filler[800]; // [HACK] Our class needs to be larger than Apple's class for the superclass change to work.
  102. }
  103. @property (nonatomic, strong) PSTCollectionViewData *collectionViewData;
  104. @property (nonatomic, strong, readonly) PSTCollectionViewExt *extVars;
  105. @property (nonatomic, readonly) id currentUpdate;
  106. @property (nonatomic, readonly) NSDictionary *visibleViewsDict;
  107. @property (nonatomic, assign) CGRect visibleBoundRects;
  108. @end
  109. // Used by PSTCollectionView for external variables.
  110. // (We need to keep the total class size equal to the UICollectionView variant)
  111. @interface PSTCollectionViewExt : NSObject
  112. @property (nonatomic, unsafe_unretained) id<PSTCollectionViewDelegate> collectionViewDelegate;
  113. @property (nonatomic, strong) PSTCollectionViewLayout *nibLayout;
  114. @property (nonatomic, strong) NSDictionary *nibCellsExternalObjects;
  115. @property (nonatomic, strong) NSDictionary *supplementaryViewsExternalObjects;
  116. @property (nonatomic, strong) NSIndexPath *touchingIndexPath;
  117. @property (nonatomic, strong) NSIndexPath *currentIndexPath;
  118. @end
  119. @implementation PSTCollectionViewExt
  120. @end
  121. const char kPSTColletionViewExt;
  122. @implementation PSTCollectionView
  123. @synthesize collectionViewLayout = _layout;
  124. @synthesize currentUpdate = _update;
  125. @synthesize visibleViewsDict = _allVisibleViewsDict;
  126. ///////////////////////////////////////////////////////////////////////////////////////////
  127. #pragma mark - NSObject
  128. static void PSTCollectionViewCommonSetup(PSTCollectionView *_self) {
  129. _self.allowsSelection = YES;
  130. _self->_indexPathsForSelectedItems = [NSMutableSet new];
  131. _self->_indexPathsForHighlightedItems = [NSMutableSet new];
  132. _self->_cellReuseQueues = [NSMutableDictionary new];
  133. _self->_supplementaryViewReuseQueues = [NSMutableDictionary new];
  134. _self->_decorationViewReuseQueues = [NSMutableDictionary new];
  135. _self->_allVisibleViewsDict = [NSMutableDictionary new];
  136. _self->_cellClassDict = [NSMutableDictionary new];
  137. _self->_cellNibDict = [NSMutableDictionary new];
  138. _self->_supplementaryViewClassDict = [NSMutableDictionary new];
  139. _self->_supplementaryViewNibDict = [NSMutableDictionary new];
  140. // add class that saves additional ivars
  141. objc_setAssociatedObject(_self, &kPSTColletionViewExt, [PSTCollectionViewExt new], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  142. }
  143. - (id)initWithFrame:(CGRect)frame {
  144. return [self initWithFrame:frame collectionViewLayout:nil];
  145. }
  146. - (id)initWithFrame:(CGRect)frame collectionViewLayout:(PSTCollectionViewLayout *)layout {
  147. if ((self = [super initWithFrame:frame])) {
  148. // Set self as the UIScrollView's delegate
  149. [super setDelegate:self];
  150. PSTCollectionViewCommonSetup(self);
  151. self.collectionViewLayout = layout;
  152. _collectionViewData = [[PSTCollectionViewData alloc] initWithCollectionView:self layout:layout];
  153. }
  154. return self;
  155. }
  156. - (id)initWithCoder:(NSCoder *)inCoder {
  157. if ((self = [super initWithCoder:inCoder])) {
  158. // Set self as the UIScrollView's delegate
  159. [super setDelegate:self];
  160. PSTCollectionViewCommonSetup(self);
  161. self.extVars.nibLayout = [inCoder decodeObjectForKey:@"UICollectionLayout"];
  162. NSDictionary *cellExternalObjects = [inCoder decodeObjectForKey:@"UICollectionViewCellPrototypeNibExternalObjects"];
  163. NSDictionary *cellNibs = [inCoder decodeObjectForKey:@"UICollectionViewCellNibDict"];
  164. for (NSString *identifier in cellNibs.allKeys) {
  165. _cellNibDict[identifier] = cellNibs[identifier];
  166. }
  167. self.extVars.nibCellsExternalObjects = cellExternalObjects;
  168. NSDictionary *supplementaryViewExternalObjects = [inCoder decodeObjectForKey:@"UICollectionViewSupplementaryViewPrototypeNibExternalObjects"];
  169. NSDictionary *supplementaryViewNibs = [inCoder decodeObjectForKey:@"UICollectionViewSupplementaryViewNibDict"];
  170. for (NSString *identifier in supplementaryViewNibs.allKeys) {
  171. _supplementaryViewNibDict[identifier] = supplementaryViewNibs[identifier];
  172. }
  173. self.extVars.supplementaryViewsExternalObjects = supplementaryViewExternalObjects;
  174. }
  175. return self;
  176. }
  177. - (void)awakeFromNib {
  178. [super awakeFromNib];
  179. PSTCollectionViewLayout *nibLayout = self.extVars.nibLayout;
  180. if (nibLayout) {
  181. self.collectionViewLayout = nibLayout;
  182. self.extVars.nibLayout = nil;
  183. }
  184. }
  185. - (NSString *)description {
  186. return [NSString stringWithFormat:@"%@ collection view layout: %@", [super description], self.collectionViewLayout];
  187. }
  188. ///////////////////////////////////////////////////////////////////////////////////////////
  189. #pragma mark - UIView
  190. - (void)layoutSubviews {
  191. [super layoutSubviews];
  192. // Adding alpha animation to make the relayouting smooth
  193. if (_collectionViewFlags.fadeCellsForBoundsChange) {
  194. CATransition *transition = [CATransition animation];
  195. transition.duration = 0.25f * PSTSimulatorAnimationDragCoefficient();
  196. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  197. transition.type = kCATransitionFade;
  198. [self.layer addAnimation:transition forKey:@"rotationAnimation"];
  199. }
  200. [_collectionViewData validateLayoutInRect:self.bounds];
  201. // update cells
  202. if (_collectionViewFlags.fadeCellsForBoundsChange) {
  203. [CATransaction begin];
  204. [CATransaction setDisableActions:YES];
  205. }
  206. if (!_collectionViewFlags.updatingLayout)
  207. [self updateVisibleCellsNow:YES];
  208. if (_collectionViewFlags.fadeCellsForBoundsChange) {
  209. [CATransaction commit];
  210. }
  211. // do we need to update contentSize?
  212. CGSize contentSize = [_collectionViewData collectionViewContentRect].size;
  213. if (!CGSizeEqualToSize(self.contentSize, contentSize)) {
  214. self.contentSize = contentSize;
  215. // if contentSize is different, we need to re-evaluate layout, bounds (contentOffset) might changed
  216. [_collectionViewData validateLayoutInRect:self.bounds];
  217. [self updateVisibleCellsNow:YES];
  218. }
  219. if (_backgroundView) {
  220. _backgroundView.frame = (CGRect){.origin=self.contentOffset, .size=self.bounds.size};
  221. }
  222. _collectionViewFlags.fadeCellsForBoundsChange = NO;
  223. _collectionViewFlags.doneFirstLayout = YES;
  224. }
  225. - (void)setFrame:(CGRect)frame {
  226. if (!CGRectEqualToRect(frame, self.frame)) {
  227. [super setFrame:frame];
  228. if ([self.collectionViewLayout shouldInvalidateLayoutForBoundsChange:self.bounds]) {
  229. [self invalidateLayout];
  230. _collectionViewFlags.fadeCellsForBoundsChange = YES;
  231. }
  232. }
  233. }
  234. - (void)setBounds:(CGRect)bounds {
  235. if (!CGRectEqualToRect(bounds, self.bounds)) {
  236. [super setBounds:bounds];
  237. if ([self.collectionViewLayout shouldInvalidateLayoutForBoundsChange:bounds]) {
  238. [self invalidateLayout];
  239. _collectionViewFlags.fadeCellsForBoundsChange = YES;
  240. }
  241. }
  242. }
  243. ///////////////////////////////////////////////////////////////////////////////////////////
  244. #pragma mark - UIScrollViewDelegate
  245. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  246. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  247. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidScroll:)]) {
  248. [delegate scrollViewDidScroll:scrollView];
  249. }
  250. }
  251. - (void)scrollViewDidZoom:(UIScrollView *)scrollView {
  252. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  253. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidZoom:)]) {
  254. [delegate scrollViewDidZoom:scrollView];
  255. }
  256. }
  257. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  258. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  259. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewWillBeginDragging:)]) {
  260. [delegate scrollViewWillBeginDragging:scrollView];
  261. }
  262. }
  263. - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
  264. // Let collectionViewLayout decide where to stop.
  265. *targetContentOffset = [[self collectionViewLayout] targetContentOffsetForProposedContentOffset:*targetContentOffset withScrollingVelocity:velocity];
  266. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  267. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewWillEndDragging:withVelocity:targetContentOffset:)]) {
  268. //if collectionViewDelegate implements this method, it may modify targetContentOffset as well
  269. [delegate scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
  270. }
  271. }
  272. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  273. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  274. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)]) {
  275. [delegate scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
  276. }
  277. // if we are in the middle of a cell touch event, perform the "touchEnded" simulation
  278. if (self.extVars.touchingIndexPath) {
  279. [self cellTouchCancelled];
  280. }
  281. }
  282. - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
  283. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  284. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewWillBeginDecelerating:)]) {
  285. [delegate scrollViewWillBeginDecelerating:scrollView];
  286. }
  287. }
  288. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  289. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  290. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)]) {
  291. [delegate scrollViewDidEndDecelerating:scrollView];
  292. }
  293. }
  294. - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
  295. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  296. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidEndScrollingAnimation:)]) {
  297. [delegate scrollViewDidEndScrollingAnimation:scrollView];
  298. }
  299. }
  300. - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
  301. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  302. if ((id)delegate != self && [delegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {
  303. return [delegate viewForZoomingInScrollView:scrollView];
  304. }
  305. return nil;
  306. }
  307. - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
  308. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  309. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewWillBeginZooming:withView:)]) {
  310. [delegate scrollViewWillBeginZooming:scrollView withView:view];
  311. }
  312. }
  313. - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
  314. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  315. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)]) {
  316. [delegate scrollViewDidEndZooming:scrollView withView:view atScale:scale];
  317. }
  318. }
  319. - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
  320. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  321. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewShouldScrollToTop:)]) {
  322. return [delegate scrollViewShouldScrollToTop:scrollView];
  323. }
  324. return YES;
  325. }
  326. - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
  327. id<PSTCollectionViewDelegate> delegate = self.extVars.collectionViewDelegate;
  328. if ((id)delegate != self && [delegate respondsToSelector:@selector(scrollViewDidScrollToTop:)]) {
  329. [delegate scrollViewDidScrollToTop:scrollView];
  330. }
  331. }
  332. ///////////////////////////////////////////////////////////////////////////////////////////
  333. #pragma mark - Public
  334. - (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
  335. NSParameterAssert(cellClass);
  336. NSParameterAssert(identifier);
  337. _cellClassDict[identifier] = cellClass;
  338. }
  339. - (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier {
  340. NSParameterAssert(viewClass);
  341. NSParameterAssert(elementKind);
  342. NSParameterAssert(identifier);
  343. NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", elementKind, identifier];
  344. _supplementaryViewClassDict[kindAndIdentifier] = viewClass;
  345. }
  346. - (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier {
  347. NSArray *topLevelObjects = [nib instantiateWithOwner:nil options:nil];
  348. #pragma unused(topLevelObjects)
  349. NSAssert(topLevelObjects.count == 1 && [topLevelObjects[0] isKindOfClass:PSTCollectionViewCell.class], @"must contain exactly 1 top level object which is a PSTCollectionViewCell");
  350. _cellNibDict[identifier] = nib;
  351. }
  352. - (void)registerNib:(UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier {
  353. NSArray *topLevelObjects = [nib instantiateWithOwner:nil options:nil];
  354. #pragma unused(topLevelObjects)
  355. NSAssert(topLevelObjects.count == 1 && [topLevelObjects[0] isKindOfClass:PSTCollectionReusableView.class], @"must contain exactly 1 top level object which is a PSTCollectionReusableView");
  356. NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", kind, identifier];
  357. _supplementaryViewNibDict[kindAndIdentifier] = nib;
  358. }
  359. - (id)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
  360. // de-queue cell (if available)
  361. NSMutableArray *reusableCells = _cellReuseQueues[identifier];
  362. PSTCollectionViewCell *cell = [reusableCells lastObject];
  363. PSTCollectionViewLayoutAttributes *attributes = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
  364. if (cell) {
  365. [reusableCells removeObjectAtIndex:reusableCells.count - 1];
  366. }else {
  367. if (_cellNibDict[identifier]) {
  368. // Cell was registered via registerNib:forCellWithReuseIdentifier:
  369. UINib *cellNib = _cellNibDict[identifier];
  370. NSDictionary *externalObjects = self.extVars.nibCellsExternalObjects[identifier];
  371. if (externalObjects) {
  372. cell = [cellNib instantiateWithOwner:self options:@{UINibExternalObjects : externalObjects}][0];
  373. }else {
  374. cell = [cellNib instantiateWithOwner:self options:nil][0];
  375. }
  376. }else {
  377. Class cellClass = _cellClassDict[identifier];
  378. // compatibility layer
  379. Class collectionViewCellClass = NSClassFromString(@"UICollectionViewCell");
  380. if (collectionViewCellClass && [cellClass isEqual:collectionViewCellClass]) {
  381. cellClass = PSTCollectionViewCell.class;
  382. }
  383. if (cellClass == nil) {
  384. @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"Class not registered for identifier %@", identifier] userInfo:nil];
  385. }
  386. if (attributes) {
  387. cell = [[cellClass alloc] initWithFrame:attributes.frame];
  388. }else {
  389. cell = [cellClass new];
  390. }
  391. }
  392. cell.collectionView = self;
  393. cell.reuseIdentifier = identifier;
  394. }
  395. [cell applyLayoutAttributes:attributes];
  396. return cell;
  397. }
  398. - (id)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
  399. NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", elementKind, identifier];
  400. NSMutableArray *reusableViews = _supplementaryViewReuseQueues[kindAndIdentifier];
  401. PSTCollectionReusableView *view = [reusableViews lastObject];
  402. if (view) {
  403. [reusableViews removeObjectAtIndex:reusableViews.count - 1];
  404. }else {
  405. if (_supplementaryViewNibDict[kindAndIdentifier]) {
  406. // supplementary view was registered via registerNib:forCellWithReuseIdentifier:
  407. UINib *supplementaryViewNib = _supplementaryViewNibDict[kindAndIdentifier];
  408. NSDictionary *externalObjects = self.extVars.supplementaryViewsExternalObjects[kindAndIdentifier];
  409. if (externalObjects) {
  410. view = [supplementaryViewNib instantiateWithOwner:self options:@{UINibExternalObjects : externalObjects}][0];
  411. }else {
  412. view = [supplementaryViewNib instantiateWithOwner:self options:nil][0];
  413. }
  414. }else {
  415. Class viewClass = _supplementaryViewClassDict[kindAndIdentifier];
  416. Class reusableViewClass = NSClassFromString(@"UICollectionReusableView");
  417. if (reusableViewClass && [viewClass isEqual:reusableViewClass]) {
  418. viewClass = PSTCollectionReusableView.class;
  419. }
  420. if (viewClass == nil) {
  421. @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"Class not registered for kind/identifier %@", kindAndIdentifier] userInfo:nil];
  422. }
  423. if (self.collectionViewLayout) {
  424. PSTCollectionViewLayoutAttributes *attributes = [self.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:elementKind atIndexPath:indexPath];
  425. if (attributes) {
  426. view = [[viewClass alloc] initWithFrame:attributes.frame];
  427. }
  428. }else {
  429. view = [viewClass new];
  430. }
  431. }
  432. view.collectionView = self;
  433. view.reuseIdentifier = identifier;
  434. }
  435. return view;
  436. }
  437. - (id)dequeueReusableOrCreateDecorationViewOfKind:(NSString *)elementKind forIndexPath:(NSIndexPath *)indexPath {
  438. NSMutableArray *reusableViews = _decorationViewReuseQueues[elementKind];
  439. PSTCollectionReusableView *view = [reusableViews lastObject];
  440. PSTCollectionViewLayout *collectionViewLayout = self.collectionViewLayout;
  441. PSTCollectionViewLayoutAttributes *attributes = [collectionViewLayout layoutAttributesForDecorationViewOfKind:elementKind atIndexPath:indexPath];
  442. if (view) {
  443. [reusableViews removeObjectAtIndex:reusableViews.count - 1];
  444. }else {
  445. NSDictionary *decorationViewNibDict = collectionViewLayout.decorationViewNibDict;
  446. NSDictionary *decorationViewExternalObjects = collectionViewLayout.decorationViewExternalObjectsTables;
  447. if (decorationViewNibDict[elementKind]) {
  448. // supplementary view was registered via registerNib:forCellWithReuseIdentifier:
  449. UINib *supplementaryViewNib = decorationViewNibDict[elementKind];
  450. NSDictionary *externalObjects = decorationViewExternalObjects[elementKind];
  451. if (externalObjects) {
  452. view = [supplementaryViewNib instantiateWithOwner:self options:@{UINibExternalObjects : externalObjects}][0];
  453. }else {
  454. view = [supplementaryViewNib instantiateWithOwner:self options:nil][0];
  455. }
  456. }else {
  457. NSDictionary *decorationViewClassDict = collectionViewLayout.decorationViewClassDict;
  458. Class viewClass = decorationViewClassDict[elementKind];
  459. Class reusableViewClass = NSClassFromString(@"UICollectionReusableView");
  460. if (reusableViewClass && [viewClass isEqual:reusableViewClass]) {
  461. viewClass = PSTCollectionReusableView.class;
  462. }
  463. if (viewClass == nil) {
  464. @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"Class not registered for identifier %@", elementKind] userInfo:nil];
  465. }
  466. if (attributes) {
  467. view = [[viewClass alloc] initWithFrame:attributes.frame];
  468. }else {
  469. view = [viewClass new];
  470. }
  471. }
  472. view.collectionView = self;
  473. view.reuseIdentifier = elementKind;
  474. }
  475. [view applyLayoutAttributes:attributes];
  476. return view;
  477. }
  478. - (NSArray *)allCells {
  479. return [[_allVisibleViewsDict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
  480. return [evaluatedObject isKindOfClass:PSTCollectionViewCell.class];
  481. }]];
  482. }
  483. - (NSArray *)visibleCells {
  484. return [[_allVisibleViewsDict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
  485. return [evaluatedObject isKindOfClass:PSTCollectionViewCell.class] && CGRectIntersectsRect(self.bounds, [evaluatedObject frame]);
  486. }]];
  487. }
  488. - (void)reloadData {
  489. if (_reloadingSuspendedCount != 0) return;
  490. [self invalidateLayout];
  491. [_allVisibleViewsDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  492. if ([obj isKindOfClass:UIView.class]) {
  493. [obj removeFromSuperview];
  494. }
  495. }];
  496. [_allVisibleViewsDict removeAllObjects];
  497. for (NSIndexPath *indexPath in _indexPathsForSelectedItems) {
  498. PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:indexPath];
  499. selectedCell.selected = NO;
  500. selectedCell.highlighted = NO;
  501. }
  502. [_indexPathsForSelectedItems removeAllObjects];
  503. [_indexPathsForHighlightedItems removeAllObjects];
  504. [self setNeedsLayout];
  505. }
  506. ///////////////////////////////////////////////////////////////////////////////////////////
  507. #pragma mark - Query Grid
  508. - (NSInteger)numberOfSections {
  509. return [_collectionViewData numberOfSections];
  510. }
  511. - (NSInteger)numberOfItemsInSection:(NSInteger)section {
  512. return [_collectionViewData numberOfItemsInSection:section];
  513. }
  514. - (PSTCollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
  515. return [[self collectionViewLayout] layoutAttributesForItemAtIndexPath:indexPath];
  516. }
  517. - (PSTCollectionViewLayoutAttributes *)layoutAttributesForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
  518. return [[self collectionViewLayout] layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
  519. }
  520. - (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point {
  521. __block NSIndexPath *indexPath = nil;
  522. [_allVisibleViewsDict enumerateKeysAndObjectsWithOptions:kNilOptions usingBlock:^(id key, id obj, BOOL *stop) {
  523. PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
  524. if (itemKey.type == PSTCollectionViewItemTypeCell) {
  525. PSTCollectionViewCell *cell = (PSTCollectionViewCell *)obj;
  526. if (CGRectContainsPoint(cell.frame, point) && cell.userInteractionEnabled) {
  527. indexPath = itemKey.indexPath;
  528. *stop = YES;
  529. }
  530. }
  531. }];
  532. return indexPath;
  533. }
  534. - (NSIndexPath *)indexPathForCell:(PSTCollectionViewCell *)cell {
  535. __block NSIndexPath *indexPath = nil;
  536. [_allVisibleViewsDict enumerateKeysAndObjectsWithOptions:kNilOptions usingBlock:^(id key, id obj, BOOL *stop) {
  537. PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
  538. if (itemKey.type == PSTCollectionViewItemTypeCell) {
  539. PSTCollectionViewCell *currentCell = (PSTCollectionViewCell *)obj;
  540. if (currentCell == cell) {
  541. indexPath = itemKey.indexPath;
  542. *stop = YES;
  543. }
  544. }
  545. }];
  546. return indexPath;
  547. }
  548. - (PSTCollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  549. // NSInteger index = [_collectionViewData globalIndexForItemAtIndexPath:indexPath];
  550. // TODO Apple uses some kind of globalIndex for this.
  551. __block PSTCollectionViewCell *cell = nil;
  552. [_allVisibleViewsDict enumerateKeysAndObjectsWithOptions:0 usingBlock:^(id key, id obj, BOOL *stop) {
  553. PSTCollectionViewItemKey *itemKey = (PSTCollectionViewItemKey *)key;
  554. if (itemKey.type == PSTCollectionViewItemTypeCell) {
  555. if ([itemKey.indexPath isEqual:indexPath]) {
  556. cell = obj;
  557. *stop = YES;
  558. }
  559. }
  560. }];
  561. return cell;
  562. }
  563. - (NSArray *)indexPathsForVisibleItems {
  564. NSArray *visibleCells = self.visibleCells;
  565. NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:visibleCells.count];
  566. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  567. PSTCollectionViewCell *cell = (PSTCollectionViewCell *)obj;
  568. [indexPaths addObject:cell.layoutAttributes.indexPath];
  569. }];
  570. return indexPaths;
  571. }
  572. // returns nil or an array of selected index paths
  573. - (NSArray *)indexPathsForSelectedItems {
  574. return [_indexPathsForSelectedItems allObjects];
  575. }
  576. // Interacting with the collection view.
  577. - (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(PSTCollectionViewScrollPosition)scrollPosition animated:(BOOL)animated {
  578. // Ensure grid is laid out; else we can't scroll.
  579. [self layoutSubviews];
  580. PSTCollectionViewLayoutAttributes *layoutAttributes = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
  581. if (layoutAttributes) {
  582. CGRect targetRect = [self makeRect:layoutAttributes.frame toScrollPosition:scrollPosition];
  583. [self scrollRectToVisible:targetRect animated:animated];
  584. }
  585. }
  586. - (CGRect)makeRect:(CGRect)targetRect toScrollPosition:(PSTCollectionViewScrollPosition)scrollPosition {
  587. // split parameters
  588. NSUInteger verticalPosition = scrollPosition&0x07; // 0000 0111
  589. NSUInteger horizontalPosition = scrollPosition&0x38; // 0011 1000
  590. if (verticalPosition != PSTCollectionViewScrollPositionNone
  591. && verticalPosition != PSTCollectionViewScrollPositionTop
  592. && verticalPosition != PSTCollectionViewScrollPositionCenteredVertically
  593. && verticalPosition != PSTCollectionViewScrollPositionBottom) {
  594. @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PSTCollectionViewScrollPosition: attempt to use a scroll position with multiple vertical positioning styles" userInfo:nil];
  595. }
  596. if (horizontalPosition != PSTCollectionViewScrollPositionNone
  597. && horizontalPosition != PSTCollectionViewScrollPositionLeft
  598. && horizontalPosition != PSTCollectionViewScrollPositionCenteredHorizontally
  599. && horizontalPosition != PSTCollectionViewScrollPositionRight) {
  600. @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PSTCollectionViewScrollPosition: attempt to use a scroll position with multiple horizontal positioning styles" userInfo:nil];
  601. }
  602. CGRect frame = self.layer.bounds;
  603. CGFloat calculateX;
  604. CGFloat calculateY;
  605. switch (verticalPosition) {
  606. case PSTCollectionViewScrollPositionCenteredVertically:
  607. calculateY = fmax(targetRect.origin.y - ((frame.size.height / 2) - (targetRect.size.height / 2)), -self.contentInset.top);
  608. targetRect = CGRectMake(targetRect.origin.x, calculateY, targetRect.size.width, frame.size.height);
  609. break;
  610. case PSTCollectionViewScrollPositionTop:
  611. targetRect = CGRectMake(targetRect.origin.x, targetRect.origin.y, targetRect.size.width, frame.size.height);
  612. break;
  613. case PSTCollectionViewScrollPositionBottom:
  614. calculateY = fmax(targetRect.origin.y - (frame.size.height - targetRect.size.height), -self.contentInset.top);
  615. targetRect = CGRectMake(targetRect.origin.x, calculateY, targetRect.size.width, frame.size.height);
  616. break;
  617. }
  618. switch (horizontalPosition) {
  619. case PSTCollectionViewScrollPositionCenteredHorizontally:
  620. calculateX = targetRect.origin.x - ((frame.size.width / 2) - (targetRect.size.width / 2));
  621. targetRect = CGRectMake(calculateX, targetRect.origin.y, frame.size.width, targetRect.size.height);
  622. break;
  623. case PSTCollectionViewScrollPositionLeft:
  624. targetRect = CGRectMake(targetRect.origin.x, targetRect.origin.y, frame.size.width, targetRect.size.height);
  625. break;
  626. case PSTCollectionViewScrollPositionRight:
  627. calculateX = targetRect.origin.x - (frame.size.width - targetRect.size.width);
  628. targetRect = CGRectMake(calculateX, targetRect.origin.y, frame.size.width, targetRect.size.height);
  629. break;
  630. }
  631. return targetRect;
  632. }
  633. ///////////////////////////////////////////////////////////////////////////////////////////
  634. #pragma mark - Touch Handling
  635. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  636. [super touchesBegan:touches withEvent:event];
  637. // reset touching state vars
  638. self.extVars.touchingIndexPath = nil;
  639. self.extVars.currentIndexPath = nil;
  640. CGPoint touchPoint = [[touches anyObject] locationInView:self];
  641. NSIndexPath *indexPath = [self indexPathForItemAtPoint:touchPoint];
  642. if (indexPath && self.allowsSelection) {
  643. if (![self highlightItemAtIndexPath:indexPath animated:YES scrollPosition:PSTCollectionViewScrollPositionNone notifyDelegate:YES])
  644. return;
  645. self.extVars.touchingIndexPath = indexPath;
  646. self.extVars.currentIndexPath = indexPath;
  647. if (!self.allowsMultipleSelection) {
  648. // temporally unhighlight background on touchesBegan (keeps selected by _indexPathsForSelectedItems)
  649. // single-select only mode only though
  650. NSIndexPath *tempDeselectIndexPath = _indexPathsForSelectedItems.anyObject;
  651. if (tempDeselectIndexPath && ![tempDeselectIndexPath isEqual:self.extVars.touchingIndexPath]) {
  652. // iOS6 UICollectionView deselects cell without notification
  653. PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:tempDeselectIndexPath];
  654. selectedCell.selected = NO;
  655. }
  656. }
  657. }
  658. }
  659. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  660. [super touchesMoved:touches withEvent:event];
  661. // allows moving between highlight and unhighlight state only if setHighlighted is not overwritten
  662. if (self.extVars.touchingIndexPath) {
  663. CGPoint touchPoint = [[touches anyObject] locationInView:self];
  664. NSIndexPath *indexPath = [self indexPathForItemAtPoint:touchPoint];
  665. // moving out of bounds
  666. if ([self.extVars.currentIndexPath isEqual:self.extVars.touchingIndexPath] &&
  667. ![indexPath isEqual:self.extVars.touchingIndexPath] &&
  668. [self unhighlightItemAtIndexPath:self.extVars.touchingIndexPath animated:YES notifyDelegate:YES shouldCheckHighlight:YES]) {
  669. self.extVars.currentIndexPath = indexPath;
  670. // moving back into the original touching cell
  671. }else if (![self.extVars.currentIndexPath isEqual:self.extVars.touchingIndexPath] &&
  672. [indexPath isEqual:self.extVars.touchingIndexPath]) {
  673. [self highlightItemAtIndexPath:self.extVars.touchingIndexPath animated:YES scrollPosition:PSTCollectionViewScrollPositionNone notifyDelegate:YES];
  674. self.extVars.currentIndexPath = self.extVars.touchingIndexPath;
  675. }
  676. }
  677. }
  678. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  679. [super touchesEnded:touches withEvent:event];
  680. if (self.extVars.touchingIndexPath) {
  681. // first unhighlight the touch operation
  682. [self unhighlightItemAtIndexPath:self.extVars.touchingIndexPath animated:YES notifyDelegate:YES];
  683. CGPoint touchPoint = [[touches anyObject] locationInView:self];
  684. NSIndexPath *indexPath = [self indexPathForItemAtPoint:touchPoint];
  685. if ([indexPath isEqual:self.extVars.touchingIndexPath]) {
  686. [self userSelectedItemAtIndexPath:indexPath];
  687. }
  688. else if (!self.allowsMultipleSelection) {
  689. NSIndexPath *tempDeselectIndexPath = _indexPathsForSelectedItems.anyObject;
  690. if (tempDeselectIndexPath && ![tempDeselectIndexPath isEqual:self.extVars.touchingIndexPath]) {
  691. [self cellTouchCancelled];
  692. }
  693. }
  694. // for pedantic reasons only - always set to nil on touchesBegan
  695. self.extVars.touchingIndexPath = nil;
  696. self.extVars.currentIndexPath = nil;
  697. }
  698. }
  699. - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  700. [super touchesCancelled:touches withEvent:event];
  701. // do not mark touchingIndexPath as nil because whoever cancelled this touch will need to signal a touch up event later
  702. if (self.extVars.touchingIndexPath) {
  703. // first unhighlight the touch operation
  704. [self unhighlightItemAtIndexPath:self.extVars.touchingIndexPath animated:YES notifyDelegate:YES];
  705. }
  706. }
  707. - (void)cellTouchCancelled {
  708. // turn on ALL the *should be selected* cells (iOS6 UICollectionView does no state keeping or other fancy optimizations)
  709. // there should be no notifications as this is a silent "turn everything back on"
  710. for (NSIndexPath *tempDeselectedIndexPath in [_indexPathsForSelectedItems copy]) {
  711. PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:tempDeselectedIndexPath];
  712. selectedCell.selected = YES;
  713. }
  714. }
  715. - (void)userSelectedItemAtIndexPath:(NSIndexPath *)indexPath {
  716. if (self.allowsMultipleSelection && [_indexPathsForSelectedItems containsObject:indexPath]) {
  717. [self deselectItemAtIndexPath:indexPath animated:YES notifyDelegate:YES];
  718. }
  719. else if (self.allowsSelection) {
  720. [self selectItemAtIndexPath:indexPath animated:YES scrollPosition:PSTCollectionViewScrollPositionNone notifyDelegate:YES];
  721. }
  722. }
  723. // select item, notify delegate (internal)
  724. - (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(PSTCollectionViewScrollPosition)scrollPosition notifyDelegate:(BOOL)notifyDelegate {
  725. if (self.allowsMultipleSelection && [_indexPathsForSelectedItems containsObject:indexPath]) {
  726. BOOL shouldDeselect = YES;
  727. if (notifyDelegate && _collectionViewFlags.delegateShouldDeselectItemAtIndexPath) {
  728. shouldDeselect = [self.delegate collectionView:self shouldDeselectItemAtIndexPath:indexPath];
  729. }
  730. if (shouldDeselect) {
  731. [self deselectItemAtIndexPath:indexPath animated:animated notifyDelegate:notifyDelegate];
  732. }
  733. }
  734. else {
  735. // either single selection, or wasn't already selected in multiple selection mode
  736. BOOL shouldSelect = YES;
  737. if (notifyDelegate && _collectionViewFlags.delegateShouldSelectItemAtIndexPath) {
  738. shouldSelect = [self.delegate collectionView:self shouldSelectItemAtIndexPath:indexPath];
  739. }
  740. if (!self.allowsMultipleSelection) {
  741. // now unselect the previously selected cell for single selection
  742. NSIndexPath *tempDeselectIndexPath = _indexPathsForSelectedItems.anyObject;
  743. if (tempDeselectIndexPath && ![tempDeselectIndexPath isEqual:indexPath]) {
  744. [self deselectItemAtIndexPath:tempDeselectIndexPath animated:YES notifyDelegate:YES];
  745. }
  746. }
  747. if (shouldSelect) {
  748. PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:indexPath];
  749. selectedCell.selected = YES;
  750. [_indexPathsForSelectedItems addObject:indexPath];
  751. [selectedCell performSelectionSegue];
  752. if (scrollPosition != PSTCollectionViewScrollPositionNone) {
  753. [self scrollToItemAtIndexPath:indexPath atScrollPosition:scrollPosition animated:animated];
  754. }
  755. if (notifyDelegate && _collectionViewFlags.delegateDidSelectItemAtIndexPath) {
  756. [self.delegate collectionView:self didSelectItemAtIndexPath:indexPath];
  757. }
  758. }
  759. }
  760. }
  761. - (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(PSTCollectionViewScrollPosition)scrollPosition {
  762. [self selectItemAtIndexPath:indexPath animated:animated scrollPosition:scrollPosition notifyDelegate:NO];
  763. }
  764. - (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated {
  765. [self deselectItemAtIndexPath:indexPath animated:animated notifyDelegate:NO];
  766. }
  767. - (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated notifyDelegate:(BOOL)notifyDelegate {
  768. BOOL shouldDeselect = YES;
  769. // deselect only relevant during multi mode
  770. if (self.allowsMultipleSelection && notifyDelegate && _collectionViewFlags.delegateShouldDeselectItemAtIndexPath) {
  771. shouldDeselect = [self.delegate collectionView:self shouldDeselectItemAtIndexPath:indexPath];
  772. }
  773. if (shouldDeselect && [_indexPathsForSelectedItems containsObject:indexPath]) {
  774. PSTCollectionViewCell *selectedCell = [self cellForItemAtIndexPath:indexPath];
  775. if (selectedCell) {
  776. if (selectedCell.selected) {
  777. selectedCell.selected = NO;
  778. }
  779. }
  780. [_indexPathsForSelectedItems removeObject:indexPath];
  781. if (notifyDelegate && _collectionViewFlags.delegateDidDeselectItemAtIndexPath) {
  782. [self.delegate collectionView:self didDeselectItemAtIndexPath:indexPath];
  783. }
  784. }
  785. }
  786. - (BOOL)highlightItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(PSTCollectionViewScrollPosition)scrollPosition notifyDelegate:(BOOL)notifyDelegate {
  787. BOOL shouldHighlight = YES;
  788. if (notifyDelegate && _collectionViewFlags.delegateShouldHighlightItemAtIndexPath) {
  789. shouldHighlight = [self.delegate collectionView:self shouldHighlightItemAtIndexPath:indexPath];
  790. }
  791. if (shouldHighlight) {
  792. PSTCollectionViewCell *highlightedCell = [self cellForItemAtIndexPath:indexPath];
  793. highlightedCell.highlighted = YES;
  794. [_indexPathsForHighlightedItems addObject:indexPath];
  795. if (scrollPosition != PSTCollectionViewScrollPositionNone) {
  796. [self scrollToItemAtIndexPath:indexPath atScrollPosition:scrollPosition animated:animated];
  797. }
  798. if (notifyDelegate && _collectionViewFlags.delegateDidHighlightItemAtIndexPath) {
  799. [self.delegate collectionView:self didHighlightItemAtIndexPath:indexPath];
  800. }
  801. }
  802. return shouldHighlight;
  803. }
  804. - (BOOL)unhighlightItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated notifyDelegate:(BOOL)notifyDelegate {
  805. return [self unhighlightItemAtIndexPath:indexPath animated:animated notifyDelegate:notifyDelegate shouldCheckHighlight:NO];
  806. }
  807. - (BOOL)unhighlightItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated notifyDelegate:(BOOL)notifyDelegate shouldCheckHighlight:(BOOL)check {
  808. if ([_indexPathsForHighlightedItems containsObject:indexPath]) {
  809. PSTCollectionViewCell *highlightedCell = [self cellForItemAtIndexPath:indexPath];
  810. // iOS6 does not notify any delegate if the cell was never highlighted (setHighlighted overwritten) during touchMoved
  811. if (check && !highlightedCell.highlighted) {
  812. return NO;
  813. }
  814. // if multiple selection or not unhighlighting a selected item we don't perform any op
  815. if (highlightedCell.highlighted && [_indexPathsForSelectedItems containsObject:indexPath]) {
  816. highlightedCell.highlighted = YES;
  817. }else {
  818. highlightedCell.highlighted = NO;
  819. }
  820. [_indexPathsForHighlightedItems removeObject:indexPath];
  821. if (notifyDelegate && _collectionViewFlags.delegateDidUnhighlightItemAtIndexPath) {
  822. [self.delegate collectionView:self didUnhighlightItemAtIndexPath:indexPath];
  823. }
  824. return YES;
  825. }
  826. return NO;
  827. }
  828. ///////////////////////////////////////////////////////////////////////////////////////////
  829. #pragma mark - Update Grid
  830. - (void)insertSections:(NSIndexSet *)sections {
  831. [self updateSections:sections updateAction:PSTCollectionUpdateActionInsert];
  832. }
  833. - (void)deleteSections:(NSIndexSet *)sections {
  834. // First delete all items
  835. NSMutableArray *paths = [NSMutableArray new];
  836. [sections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  837. for (int i = 0; i < [self numberOfItemsInSection:idx]; ++i) {
  838. [paths addObject:[NSIndexPath indexPathForItem:i inSection:idx]];
  839. }
  840. }];
  841. [self deleteItemsAtIndexPaths:paths];
  842. // Then delete the section.
  843. [self updateSections:sections updateAction:PSTCollectionUpdateActionDelete];
  844. }
  845. - (void)reloadSections:(NSIndexSet *)sections {
  846. [self updateSections:sections updateAction:PSTCollectionUpdateActionReload];
  847. }
  848. - (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection {
  849. NSMutableArray *moveUpdateItems = [self arrayForUpdateAction:PSTCollectionUpdateActionMove];
  850. [moveUpdateItems addObject:
  851. [[PSTCollectionViewUpdateItem alloc] initWithInitialIndexPath:[NSIndexPath indexPathForItem:NSNotFound inSection:section]
  852. finalIndexPath:[NSIndexPath indexPathForItem:NSNotFound inSection:newSection]
  853. updateAction:PSTCollectionUpdateActionMove]];
  854. if (!_collectionViewFlags.updating) {
  855. [self setupCellAnimations];
  856. [self endItemAnimations];
  857. }
  858. }
  859. - (void)insertItemsAtIndexPaths:(NSArray *)indexPaths {
  860. [self updateRowsAtIndexPaths:indexPaths updateAction:PSTCollectionUpdateActionInsert];
  861. }
  862. - (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths {
  863. [self updateRowsAtIndexPaths:indexPaths updateAction:PSTCollectionUpdateActionDelete];
  864. }
  865. - (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths {
  866. [self updateRowsAtIndexPaths:indexPaths updateAction:PSTCollectionUpdateActionReload];
  867. }
  868. - (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath {
  869. NSMutableArray *moveUpdateItems = [self arrayForUpdateAction:PSTCollectionUpdateActionMove];
  870. [moveUpdateItems addObject:
  871. [[PSTCollectionViewUpdateItem alloc] initWithInitialIndexPath:indexPath
  872. finalIndexPath:newIndexPath
  873. updateAction:PSTCollectionUpdateActionMove]];
  874. if (!_collectionViewFlags.updating) {
  875. [self setupCellAnimations];
  876. [self endItemAnimations];
  877. }
  878. }
  879. - (void)performBatchUpdates:(void (^)(void))updates completion:(void (^)(BOOL finished))completion {
  880. [self setupCellAnimations];
  881. if (updates) updates();
  882. if (completion) _updateCompletionHandler = completion;
  883. [self endItemAnimations];
  884. }
  885. ///////////////////////////////////////////////////////////////////////////////////////////
  886. #pragma mark - Properties
  887. - (void)setBackgroundView:(UIView *)backgroundView {
  888. if (backgroundView != _backgroundView) {
  889. [_backgroundView removeFromSuperview];
  890. _backgroundView = backgroundView;
  891. backgroundView.frame = (CGRect){.origin=self.contentOffset, .size=self.bounds.size};
  892. backgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
  893. [self addSubview:backgroundView];
  894. [self sendSubviewToBack:backgroundView];
  895. }
  896. }
  897. - (void)setCollectionViewLayout:(PSTCollectionViewLayout *)layout animated:(BOOL)animated {
  898. if (layout == _layout) return;
  899. // not sure it was it original code, but here this prevents crash
  900. // in case we switch layout before previous one was initially loaded
  901. if (CGRectIsEmpty(self.bounds) || !_collectionViewFlags.doneFirstLayout) {
  902. _layout.collectionView = nil;
  903. _collectionViewData = [[PSTCollectionViewData alloc] initWithCollectionView:self layout:layout];
  904. layout.collectionView = self;
  905. _layout = layout;
  906. // originally the use method
  907. // _setNeedsVisibleCellsUpdate:withLayoutAttributes:
  908. // here with CellsUpdate set to YES and LayoutAttributes parameter set to NO
  909. // inside this method probably some flags are set and finally
  910. // setNeedsDisplay is called
  911. _collectionViewFlags.scheduledUpdateVisibleCells = YES;
  912. _collectionViewFlags.scheduledUpdateVisibleCellLayoutAttributes = NO;
  913. [self setNeedsDisplay];
  914. }
  915. else {
  916. layout.collectionView = self;
  917. _collectionViewData = [[PSTCollectionViewData alloc] initWithCollectionView:self layout:layout];
  918. [_collectionViewData prepareToLoadData];
  919. NSArray *previouslySelectedIndexPaths = [self indexPathsForSelectedItems];
  920. NSMutableSet *selectedCellKeys = [NSMutableSet setWithCapacity:previouslySelectedIndexPaths.count];
  921. for (NSIndexPath *indexPath in previouslySelectedIndexPaths) {
  922. [selectedCellKeys addObject:[PSTCollectionViewItemKey collectionItemKeyForCellWithIndexPath:indexPath]];
  923. }
  924. NSArray *previouslyVisibleItemsKeys = [_allVisibleViewsDict allKeys];
  925. NSSet *previouslyVisibleItemsKeysSet = [NSSet setWithArray:previouslyVisibleItemsKeys];
  926. NSMutableSet *previouslyVisibleItemsKeysSetMutable = [NSMutableSet setWithArray:previouslyVisibleItemsKeys];
  927. if ([selectedCellKeys intersectsSet:selectedCellKeys]) {
  928. [previouslyVisibleItemsKeysSetMutable intersectSet:previouslyVisibleItemsKeysSetMutable];
  929. }
  930. [self bringSubviewToFront:_allVisibleViewsDict[[previouslyVisibleItemsKeysSetMutable anyObject]]];
  931. CGPoint targetOffset = self.contentOffset;
  932. CGPoint centerPoint = CGPointMake(self.bounds.origin.x + self.bounds.size.width / 2.f,
  933. self.bounds.origin.y + self.bounds.size.height / 2.f);
  934. NSIndexPath *centerItemIndexPath = [self indexPathForItemAtPoint:centerPoint];
  935. if (!centerItemIndexPath) {
  936. NSArray *visibleItems = [self indexPathsForVisibleItems];
  937. if (visibleItems.count > 0) {
  938. centerItemIndexPath = visibleItems[visibleItems.count / 2];
  939. }
  940. }
  941. if (centerItemIndexPath) {
  942. PSTCollectionViewLayoutAttributes *layoutAttributes = [layout layoutAttributesForItemAtIndexPath:centerItemIndexPath];
  943. if (layoutAttributes) {
  944. PSTCollectionViewScrollPosition scrollPosition = PSTCollectionViewScrollPositionCenteredVertically|PSTCollectionViewScrollPositionCenteredHorizontally;
  945. CGRect targetRect = [self makeRect:layoutAttributes.frame toScrollPosition:scrollPosition];
  946. targetOffset = CGPointMake(fmax(0.f, targetRect.origin.x), fmax(0.f, targetRect.origin.y));
  947. }
  948. }
  949. CGRect newlyBounds = CGRectMake(targetOffset.x, targetOffset.y, self.bounds.size.width, self.bounds.size.height);
  950. NSArray *newlyVisibleLayoutAttrs = [_collectionViewData layoutAttributesForElementsInRect:newlyBounds];
  951. NSMutableDictionary *layoutInterchangeData = [NSMutableDictionary dictionaryWithCapacity:
  952. newlyVisibleLayoutAttrs.count + previouslyVisibleItemsKeysSet.count];
  953. NSMutableSet *newlyVisibleItemsKeys = [NSMutableSet set];
  954. for (PSTCollectionViewLayoutAttributes *attr in newlyVisibleLayoutAttrs) {
  955. PSTCollectionViewItemKey *newKey = [PSTCollectionViewItemKey collectionItemKeyForLayoutAttributes:attr];
  956. [newlyVisibleItemsKeys addObject:newKey];
  957. PSTCollectionViewLayoutAttributes *prevAttr = nil;
  958. PSTCollectionViewLayoutAttributes *newAttr = nil;
  959. if (newKey.type == PSTCollectionViewItemTypeDecorationView) {
  960. prevAttr = [self.collectionViewLayout layoutAttributesForDecorationViewOfKind:attr.representedElementKind
  961. atIndexPath:newKey.indexPath];
  962. newAttr = [layout layoutAttributesForDecorationViewOfKind:attr.representedElementKind
  963. atIndexPath:newKey.indexPath];
  964. }
  965. else if (newKey.type == PSTCollectionViewItemTypeCell) {
  966. prevAttr = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:newKey.indexPath];
  967. newAttr = [layout layoutAttributesForItemAtIndexPath:newKey.indexPath];
  968. }
  969. else {
  970. prevAttr = [self.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:attr.representedElementKind
  971. atIndexPath:newKey.indexPath];
  972. newAttr = [layout layoutAttributesForSupplementaryViewOfKind:attr.representedElementKind
  973. atIndexPath:newKey.indexPath];
  974. }
  975. if (prevAttr != nil && newAttr != nil) {
  976. layoutInterchangeData[newKey] = @{@"previousLayoutInfos": prevAttr, @"newLayoutInfos": newAttr};
  977. }
  978. }
  979. for (PSTCollectionViewItemKey *key in previouslyVisibleItemsKeysSet) {
  980. PSTCollectionViewLayoutAttributes *prevAttr = nil;
  981. PSTCollectionViewLayoutAttributes *newAttr = nil;
  982. if (key.type == PSTCollectionViewItemTypeDecorationView) {
  983. PSTCollectionReusableView *decorView = _allVisibleViewsDict[key];
  984. prevAttr = [self.collectionViewLayout layoutAttributesForDecorationViewOfKind:decorView.reuseIdentifier
  985. atIndexPath:key.indexPath];
  986. newAttr = [layout layoutAttributesForDecorationViewOfKind:decorView.reuseIdentifier
  987. atIndexPath:key.indexPath];
  988. }
  989. else if (key.type == PSTCollectionViewItemTypeCell) {
  990. prevAttr = [self.collectionViewLayout layoutAttributesForItemAtIndexPath:key.indexPath];
  991. newAttr = [layout layoutAttributesForItemAtIndexPath:key.indexPath];
  992. }
  993. else if (key.type == PSTCollectionViewItemTypeSupplementaryView) {
  994. PSTCollectionReusableView *suuplView = _allVisibleViewsDict[key];
  995. prevAttr = [self.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:suuplView.layoutAttributes.representedElementKind
  996. atIndexPath:key.indexPath];
  997. newAttr = [layout layoutAttributesForSupplementaryViewOfKind:suuplView.layoutAttributes.representedElementKind
  998. atIndexPath:key.indexPath];
  999. }
  1000. NSMutableDictionary *layoutInterchangeDataValue = [NSMutableDictionary dictionary];
  1001. if (prevAttr) layoutInterchangeDataValue[@"previousLayoutInfos"] = prevAttr;
  1002. if (newAttr) layoutInterchangeDataValue[@"newLayoutInfos"] = newAttr;
  1003. layoutInterchangeData[key] = layoutInterchangeDataValue;
  1004. }
  1005. for (PSTCollectionViewItemKey *key in [layoutInterchangeData keyEnumerator]) {
  1006. if (key.type == PSTCollectionViewItemTypeCell) {
  1007. PSTCollectionViewCell *cell = _allVisibleViewsDict[key];
  1008. if (!cell) {
  1009. cell = [self createPreparedCellForItemAtIndexPath:key.indexPath
  1010. withLayoutAttributes:layoutInterchangeData[key][@"previousLayoutInfos"]];
  1011. _allVisibleViewsDict[key] = cell;
  1012. [self addControlledSubview:cell];
  1013. }
  1014. else [cell applyLayoutAttributes:layoutInterchangeData[key][@"previousLayoutInfos"]];
  1015. }
  1016. else if (key.type == PSTCollectionViewItemTypeSupplementaryView) {
  1017. PSTCollectionReusableView *view = _allVisibleViewsDict[key];
  1018. if (!view) {
  1019. PSTCollectionViewLayoutAttributes *attrs = layoutInterchangeData[key][@"previousLayoutInfos"];
  1020. view = [self createPreparedSupplementaryViewForElementOfKind:attrs.representedElementKind
  1021. atIndexPath:attrs.indexPath
  1022. withLayoutAttributes:attrs];
  1023. _allVisibleViewsDict[key] = view;
  1024. [self addControlledSubview:view];
  1025. }
  1026. }
  1027. else if (key.type == PSTCollectionViewItemTypeDecorationView) {
  1028. PSTCollectionReusableView *view = _allVisibleViewsDict[key];
  1029. if (!view) {
  1030. PSTCollectionViewLayoutAttributes *attrs = layoutInterchangeData[key][@"previousLayoutInfos"];
  1031. view = [self dequeueReusableOrCreateDecorationViewOfKind:attrs.representedElementKind forIndexPath:attrs.indexPath];
  1032. _allVisibleViewsDict[key] = view;
  1033. [self addControlledSubview:view];
  1034. }
  1035. }
  1036. };
  1037. CGRect contentRect = [_collectionViewData collectionViewContentRect];
  1038. void (^applyNewLayoutBlock)(void) = ^{
  1039. NSEnumerator *keys = [layoutInterchangeData keyEnumerator];
  1040. for (PSTCollectionViewItemKey *key in keys) {
  1041. // TODO: This is most likely not 100% the same time as in UICollectionView. Needs to be investigated.
  1042. PSTCollectionViewCell *cell = (PSTCollectionViewCell *)self->_allVisibleViewsDict[key];
  1043. [cell willTransitionFromLayout:self->_layout toLayout:layout];
  1044. [cell applyLayoutAttributes:layoutInterchangeData[key][@"newLayoutInfos"]];
  1045. [cell didTransitionFromLayout:self->_layout toLayout:layout];
  1046. }
  1047. };
  1048. void (^freeUnusedViews)(void) = ^{
  1049. NSMutableSet *toRemove = [NSMutableSet set];
  1050. for (PSTCollectionViewItemKey *key in [self->_allVisibleViewsDict keyEnumerator]) {
  1051. if (![newlyVisibleItemsKeys containsObject:key]) {
  1052. if (key.type == PSTCollectionViewItemTypeCell) {
  1053. [self reuseCell:self->_allVisibleViewsDict[key]];
  1054. [toRemove addObject:key];
  1055. }
  1056. else if (key.type == PSTCollectionViewItemTypeSupplementaryView) {
  1057. [self reuseSupplementaryView:self->_allVisibleViewsDict[key]];
  1058. [toRemove addObject:key];
  1059. }
  1060. else if (key.type == PSTCollectionViewItemTypeDecorationView) {
  1061. [self reuseDecorationView:self->_allVisibleViewsDict[key]];
  1062. [toRemove addObject:key];
  1063. }
  1064. }
  1065. }
  1066. for (id key in toRemove)
  1067. [self->_allVisibleViewsDict removeObjectForKey:key];
  1068. };
  1069. if (animated) {
  1070. [UIView animateWithDuration:.3 animations:^{
  1071. self->_collectionViewFlags.updatingLayout = YES;
  1072. self.contentOffset = targetOffset;
  1073. self.contentSize = contentRect.size;
  1074. applyNewLayoutBlock();
  1075. } completion:^(BOOL finished) {
  1076. freeUnusedViews();
  1077. self->_collectionViewFlags.updatingLayout = NO;
  1078. // layout subviews for updating content offset or size while updating layout
  1079. if (!CGPointEqualToPoint(self.contentOffset, targetOffset)
  1080. || !CGSizeEqualToSize(self.contentSize, contentRect.size)) {
  1081. [self layoutSubviews];
  1082. }
  1083. }];
  1084. }
  1085. else {
  1086. self.contentOffset = targetOffset;
  1087. self.contentSize = contentRect.size;
  1088. applyNewLayoutBlock();
  1089. freeUnusedViews();
  1090. }
  1091. _layout.collectionView = nil;
  1092. _layout = layout;
  1093. }
  1094. }
  1095. - (void)setCollectionViewLayout:(PSTCollectionViewLayout *)layout {
  1096. [self setCollectionViewLayout:layout animated:NO];
  1097. }
  1098. - (id<PSTCollectionViewDelegate>)delegate {
  1099. return self.extVars.collectionViewDelegate;
  1100. }
  1101. - (void)setDelegate:(id<PSTCollectionViewDelegate>)delegate {
  1102. self.extVars.collectionViewDelegate = delegate;
  1103. // Managing the Selected Cells
  1104. _collectionViewFlags.delegateShouldSelectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:shouldSelectItemAtIndexPath:)];
  1105. _collectionViewFlags.delegateDidSelectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)];
  1106. _collectionViewFlags.delegateShouldDeselectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:shouldDeselectItemAtIndexPath:)];
  1107. _collectionViewFlags.delegateDidDeselectItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didDeselectItemAtIndexPath:)];
  1108. // Managing Cell Highlighting
  1109. _collectionViewFlags.delegateShouldHighlightItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:shouldHighlightItemAtIndexPath:)];
  1110. _collectionViewFlags.delegateDidHighlightItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didHighlightItemAtIndexPath:)];
  1111. _collectionViewFlags.delegateDidUnhighlightItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:didUnhighlightItemAtIndexPath:)];
  1112. // Tracking the Removal of Views
  1113. _collectionViewFlags.delegateDidEndDisplayingCell = [self.delegate respondsToSelector:@selector(collectionView:didEndDisplayingCell:forItemAtIndexPath:)];
  1114. _collectionViewFlags.delegateDidEndDisplayingSupplementaryView = [self.delegate respondsToSelector:@selector(collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:)];
  1115. // Managing Actions for Cells
  1116. _collectionViewFlags.delegateSupportsMenus = [self.delegate respondsToSelector:@selector(collectionView:shouldShowMenuForItemAtIndexPath:)];
  1117. // These aren't present in the flags which is a little strange. Not adding them because that will mess with byte alignment which will affect cross compatibility.
  1118. // The flag names are guesses and are there for documentation purposes.
  1119. // _collectionViewFlags.delegateCanPerformActionForItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:canPerformAction:forItemAtIndexPath:withSender:)];
  1120. // _collectionViewFlags.delegatePerformActionForItemAtIndexPath = [self.delegate respondsToSelector:@selector(collectionView:performAction:forItemAtIndexPath:withSender:)];
  1121. }
  1122. // Might be overkill since two are required and two are handled by PSTCollectionViewData leaving only one flag we actually need to check for
  1123. - (void)setDataSource:(id<PSTCollectionViewDataSource>)dataSource {
  1124. if (dataSource != _dataSource) {
  1125. _dataSource = dataSource;
  1126. // Getting Item and Section Metrics
  1127. _collectionViewFlags.dataSourceNumberOfSections = [_dataSource respondsToSelector:@selector(numberOfSectionsInCollectionView:)];
  1128. // Getting Views for Items
  1129. _collectionViewFlags.dataSourceViewForSupplementaryElement = [_dataSource respondsToSelector:@selector(collectionView:viewForSupplementaryElementOfKind:atIndexPath:)];
  1130. }
  1131. }
  1132. - (BOOL)allowsSelection {
  1133. return _collectionViewFlags.allowsSelection;
  1134. }
  1135. - (void)setAllowsSelection:(BOOL)allowsSelection {
  1136. _collectionViewFlags.allowsSelection = allowsSelection;
  1137. }
  1138. - (BOOL)allowsMultipleSelection {
  1139. return _collectionViewFlags.allowsMultipleSelection;
  1140. }
  1141. - (void)setAllowsMultipleSelection:(BOOL)allowsMultipleSelection {
  1142. _collectionViewFlags.allowsMultipleSelection = allowsMultipleSelection;
  1143. // Deselect all objects if allows multiple selection is false
  1144. if (!allowsMultipleSelection && _indexPathsForSelectedItems.count) {
  1145. // Note: Apple's implementation leaves a mostly random item selected. Presumably they
  1146. // have a good reason for this, but I guess it's just skipping the last or first index.
  1147. for (NSIndexPath *selectedIndexPath in [_indexPathsForSelectedItems copy]) {
  1148. if (_indexPathsForSelectedItems.count == 1) continue;
  1149. [self deselectItemAtIndexPath:selectedIndexPath animated:YES notifyDelegate:YES];
  1150. }
  1151. }
  1152. }
  1153. - (CGRect)visibleBoundRects {
  1154. // in original UICollectionView implementation they
  1155. // check for _visibleBounds and can union self.bounds
  1156. // with this value. Don't know the meaning of _visibleBounds however.
  1157. return self.bounds;
  1158. }
  1159. ///////////////////////////////////////////////////////////////////////////////////////////
  1160. #pragma mark - Private
  1161. - (PSTCollectionViewExt *)extVars {
  1162. return objc_getAssociatedObject(self, &kPSTColletionViewExt);
  1163. }
  1164. - (void)invalidateLayout {
  1165. [self.collectionViewLayout invalidateLayout];
  1166. [self.collectionViewData invalidate]; // invalidate layout cache
  1167. }
  1168. // update currently visible cells, fetches new cells if needed
  1169. // TODO: use now parameter.
  1170. - (void)updateVisibleCellsNow:(BOOL)now {
  1171. NSArray *layoutAttributesArray = [_collectionViewData layoutAttributesForElementsInRect:self.bounds];
  1172. if (layoutAttributesArray == nil || layoutAttributesArray.count == 0) {
  1173. // If our layout source isn't providing any layout information, we should just
  1174. // stop, otherwise we'll blow away all the currently existing cells.
  1175. return;
  1176. }
  1177. // create ItemKey/Attributes dictionary
  1178. NSMutableDictionary *itemKeysToAddDict = [NSMutableDictionary dictionary];
  1179. // Add new cells.
  1180. for (PSTCollectionViewLayoutAttributes *layoutAttributes in layoutAttributesArray) {
  1181. PSTCollectionViewItemKey *itemKey = [PSTCollectionViewItemKey collectionItemKeyForLayoutAttributes:layoutAttributes];
  1182. itemKeysToAddDict[itemKey] = layoutAttributes;
  1183. // check if cell is in visible dict; add it if not.
  1184. PSTCollectionReusableView *view = _allVisibleViewsDict[itemKey];
  1185. if (!view) {
  1186. if (itemKey.type == PSTCollectionViewItemTypeCell) {
  1187. view = [self createPreparedCellForItemAtIndexPath:itemKey.indexPath withLayoutAttributes:layoutAttributes];
  1188. }else if (itemKey.type == PSTCollectionViewItemTypeSupplementaryView) {
  1189. view = [self createPreparedSupplementaryViewForElementOfKind:layoutAttributes.representedElementKind
  1190. atIndexPath:layoutAttributes.indexPath
  1191. withLayoutAttributes:layoutAttributes];
  1192. }else if (itemKey.type == PSTCollectionViewItemTypeDecorationView) {
  1193. view = [self dequeueReusableOrCreateDecorationViewOfKind:layoutAttributes.representedElementKind forIndexPath:layoutAttributes.indexPath];
  1194. }
  1195. // Supplementary views are optional
  1196. if (view) {
  1197. _allVisibleViewsDict[itemKey] = view;
  1198. [self addControlledSubview:view];
  1199. // Always apply attributes. Fixes #203.
  1200. [view applyLayoutAttributes:layoutAttributes];
  1201. }
  1202. }else {
  1203. // just update cell
  1204. [view applyLayoutAttributes:layoutAttributes];
  1205. }
  1206. }
  1207. // Detect what items should be removed and queued back.
  1208. NSMutableSet *allVisibleItemKeys = [NSMutableSet setWithArray:[_allVisibleViewsDict allKeys]];
  1209. [allVisibleItemKeys minusSet:[NSSet setWithArray:[itemKeysToAddDict allKeys]]];
  1210. // Finally remove views that have not been processed and prepare them for re-use.
  1211. for (PSTCollectionViewItemKey *itemKey in allVisibleItemKeys) {
  1212. PSTCollectionReusableView *reusableView = _allVisibleViewsDict[itemKey];
  1213. if (reusableView) {
  1214. [reusableView removeFromSuperview];
  1215. [_allVisibleViewsDict removeObjectForKey:itemKey];
  1216. if (itemKey.type == PSTCollectionViewItemTypeCell) {
  1217. if (_collectionViewFlags.delegateDidEndDisplayingCell) {
  1218. [self.delegate collectionView:self didEndDisplayingCell:(PSTCollectionViewCell *)reusableView forItemAtIndexPath:itemKey.indexPath];
  1219. }
  1220. [self reuseCell:(PSTCollectionViewCell *)reusableView];
  1221. }
  1222. else if (itemKey.type == PSTCollectionViewItemTypeSupplementaryView) {
  1223. if (_collectionViewFlags.delegateDidEndDisplayingSupplementaryView) {
  1224. [self.delegate collectionView:self didEndDisplayingSupplementaryView:reusableView forElementOfKind:itemKey.identifier atIndexPath:itemKey.indexPath];
  1225. }
  1226. [self reuseSupplementaryView:reusableView];
  1227. }
  1228. else if (itemKey.type == PSTCollectionViewItemTypeDecorationView) {
  1229. [self reuseDecorationView:reusableView];
  1230. }
  1231. }
  1232. }
  1233. }
  1234. // fetches a cell from the dataSource and sets the layoutAttributes
  1235. - (PSTCollectionViewCell *)createPreparedCellForItemAtIndexPath:(NSIndexPath *)indexPath withLayoutAttributes:(PSTCollectionViewLayoutAttributes *)layoutAttributes {
  1236. PSTCollectionViewCell *cell = [self.dataSource collectionView:self cellForItemAtIndexPath:indexPath];
  1237. // Apply attributes
  1238. [cell applyLayoutAttributes:layoutAttributes];
  1239. // reset selected/highlight state
  1240. [cell setHighlighted:[_indexPathsForHighlightedItems containsObject:indexPath]];
  1241. [cell setSelected:[_indexPathsForSelectedItems containsObject:indexPath]];
  1242. // voiceover support
  1243. cell.isAccessibilityElement = YES;
  1244. return cell;
  1245. }
  1246. - (PSTCollectionReusableView *)createPreparedSupplementaryViewForElementOfKind:(NSString *)kind
  1247. atIndexPath:(NSIndexPath *)indexPath
  1248. withLayoutAttributes:(PSTCollectionViewLayoutAttributes *)layoutAttributes {
  1249. if (_collectionViewFlags.dataSourceViewForSupplementaryElement) {
  1250. PSTCollectionReusableView *view = [self.dataSource collectionView:self
  1251. viewForSupplementaryElementOfKind:kind
  1252. atIndexPath:indexPath];
  1253. [view applyLayoutAttributes:layoutAttributes];
  1254. return view;
  1255. }
  1256. return nil;
  1257. }
  1258. // @steipete optimization
  1259. - (void)queueReusableView:(PSTCollectionReusableView *)reusableView inQueue:(NSMutableDictionary *)queue withIdentifier:(NSString *)identifier {
  1260. NSParameterAssert(identifier.length > 0);
  1261. [reusableView removeFromSuperview];
  1262. [reusableView prepareForReuse];
  1263. // enqueue cell
  1264. NSMutableArray *reuseableViews = queue[identifier];
  1265. if (!reuseableViews) {
  1266. reuseableViews = [NSMutableArray array];
  1267. queue[identifier] = reuseableViews;
  1268. }
  1269. [reuseableViews addObject:reusableView];
  1270. }
  1271. // enqueue cell for reuse
  1272. - (void)reuseCell:(PSTCollectionViewCell *)cell {
  1273. [self queueReusableView:cell inQueue:_cellReuseQueues withIdentifier:cell.reuseIdentifier];
  1274. }
  1275. // enqueue supplementary view for reuse
  1276. - (void)reuseSupplementaryView:(PSTCollectionReusableView *)supplementaryView {
  1277. NSString *kindAndIdentifier = [NSString stringWithFormat:@"%@/%@", supplementaryView.layoutAttributes.elementKind, supplementaryView.reuseIdentifier];
  1278. [self queueReusableView:supplementaryView inQueue:_supplementaryViewReuseQueues withIdentifier:kindAndIdentifier];
  1279. }
  1280. // enqueue decoration view for reuse
  1281. - (void)reuseDecorationView:(PSTCollectionReusableView *)decorationView {
  1282. [self queueReusableView:decorationView inQueue:_decorationViewReuseQueues withIdentifier:decorationView.reuseIdentifier];
  1283. }
  1284. - (void)addControlledSubview:(PSTCollectionReusableView *)subview {
  1285. // avoids placing views above the scroll indicator
  1286. // If the collection view is not displaying scrollIndicators then self.subviews.count can be 0.
  1287. // We take the max to ensure we insert at a non negative index because a negative index will silently fail to insert the view
  1288. NSInteger insertionIndex = MAX((NSInteger)(self.subviews.count - (self.dragging ? 1 : 0)), 0);
  1289. [self insertSubview:subview atIndex:insertionIndex];
  1290. UIView *scrollIndicatorView = nil;
  1291. if (self.dragging) {
  1292. scrollIndicatorView = [self.subviews lastObject];
  1293. }
  1294. NSMutableArray *floatingViews = [[NSMutableArray alloc] init];
  1295. for (UIView *uiView in self.subviews) {
  1296. if ([uiView isKindOfClass:PSTCollectionReusableView.class] && [[(PSTCollectionReusableView *)uiView layoutAttributes] zIndex] > 0) {
  1297. [floatingViews addObject:uiView];
  1298. }
  1299. }
  1300. [floatingViews sortUsingComparator:^NSComparisonResult(PSTCollectionReusableView *obj1, PSTCollectionReusableView *obj2) {
  1301. CGFloat z1 = [[obj1 layoutAttributes] zIndex];
  1302. CGFloat z2 = [[obj2 layoutAttributes] zIndex];
  1303. if (z1 > z2) {
  1304. return (NSComparisonResult)NSOrderedDescending;
  1305. }else if (z1 < z2) {
  1306. return (NSComparisonResult)NSOrderedAscending;
  1307. }else {
  1308. return (NSComparisonResult)NSOrderedSame;
  1309. }
  1310. }];
  1311. for (PSTCollectionReusableView *uiView in floatingViews) {
  1312. [self bringSubviewToFront:uiView];
  1313. }
  1314. if (floatingViews.count && scrollIndicatorView) {
  1315. [self bringSubviewToFront:scrollIndicatorView];
  1316. }
  1317. }
  1318. ///////////////////////////////////////////////////////////////////////////////////////////
  1319. #pragma mark - Updating grid internal functionality
  1320. - (void)suspendReloads {
  1321. _reloadingSuspendedCount++;
  1322. }
  1323. - (void)resumeReloads {
  1324. if (0 < _reloadingSuspendedCount) _reloadingSuspendedCount--;
  1325. }
  1326. - (NSMutableArray *)arrayForUpdateAction:(PSTCollectionUpdateAction)updateAction {
  1327. NSMutableArray *updateActions = nil;
  1328. switch (updateAction) {
  1329. case PSTCollectionUpdateActionInsert:
  1330. if (!_insertItems) _insertItems = [NSMutableArray new];
  1331. updateActions = _insertItems;
  1332. break;
  1333. case PSTCollectionUpdateActionDelete:
  1334. if (!_deleteItems) _deleteItems = [NSMutableArray new];
  1335. updateActions = _deleteItems;
  1336. break;
  1337. case PSTCollectionUpdateActionMove:
  1338. if (!_moveItems) _moveItems = [NSMutableArray new];
  1339. updateActions = _moveItems;
  1340. break;
  1341. case PSTCollectionUpdateActionReload:
  1342. if (!_reloadItems) _reloadItems = [NSMutableArray new];
  1343. updateActions = _reloadItems;
  1344. break;
  1345. default: break;
  1346. }
  1347. return updateActions;
  1348. }
  1349. - (void)prepareLayoutForUpdates {
  1350. NSMutableArray *array = [[NSMutableArray alloc] init];
  1351. [array addObjectsFromArray:[_originalDeleteItems sortedArrayUsingSelector:@selector(inverseCompareIndexPaths:)]];
  1352. [array addObjectsFromArray:[_originalInsertItems sortedArrayUsingSelector:@selector(compareIndexPaths:)]];
  1353. [array addObjectsFromArray:[_reloadItems sortedArrayUsingSelector:@selector(compareIndexPaths:)]];
  1354. [array addObjectsFromArray:[_moveItems sortedArrayUsingSelector:@selector(compareIndexPaths:)]];
  1355. [_layout prepareForCollectionViewUpdates:array];
  1356. }
  1357. - (void)updateWithItems:(NSArray *)items {
  1358. [self prepareLayoutForUpdates];
  1359. NSMutableArray *animations = [[NSMutableArray alloc] init];
  1360. NSMutableDictionary *newAllVisibleView = [[NSMutableDictionary alloc] init];
  1361. NSMutableDictionary *viewsToRemove = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  1362. [NSMutableArray array], @(PSTCollectionViewItemTypeCell),
  1363. [NSMutableArray array], @(PSTCollectionViewItemTypeDecorationView),
  1364. [NSMutableArray array], @(PSTCollectionViewItemTypeSupplementaryView), nil];
  1365. for (PSTCollectionViewUpdateItem *updateItem in items) {
  1366. if (updateItem.isSectionOperation && updateItem.updateAction != PSTCollectionUpdateActionDelete) continue;
  1367. if (updateItem.isSectionOperation && updateItem.updateAction == PSTCollectionUpdateActionDelete) {
  1368. NSInteger numberOfBeforeSection;
  1369. // = [_update[@"oldModel"] numberOfItemsInSection:updateItem.indexPathBeforeUpdate.section];
  1370. for (NSInteger i = 0; i < numberOfBeforeSection; i++) {
  1371. NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:updateItem.indexPathBeforeUpdate.section];
  1372. PSTCollectionViewLayoutAttributes *finalAttrs = [_layout finalLayoutAttributesForDisappearingItemAtIndexPath:indexPath];
  1373. PSTCollectionViewItemKey *key = [PSTCollectionViewItemKey collectionItemKeyForCellWithIndexPath:indexPath];
  1374. PSTCollectionReusableView *view = _allVisibleViewsDict[key];
  1375. if (view) {
  1376. PSTCollectionViewLayoutAttributes *startAttrs = view.layoutAttributes;
  1377. if (!finalAttrs) {
  1378. finalAttrs = [startAttrs copy];
  1379. finalAttrs.alpha = 0;
  1380. }
  1381. [animations addObject:@{@"view" : view, @"previousLayoutInfos" : startAttrs, @"newLayoutInfos" : finalAttrs}];
  1382. [_allVisibleViewsDict removeObjectForKey:key];
  1383. [(NSMutableArray *)viewsToRemove[@(key.type)] addObject:view];
  1384. }
  1385. }
  1386. continue;
  1387. }
  1388. if (updateItem.updateAction == PSTCollectionUpdateActionDelete) {
  1389. NSIndexPath *indexPath = updateItem.indexPathBeforeUpdate;
  1390. PSTCollectionViewLayoutAttributes *finalAttrs = [_layout finalLayoutAttributesForDisappearingItemAtIndexPath:indexPath];
  1391. PSTCollectionViewItemKey *key = [PSTCollectionViewItemKey collectionItemKeyForCellWithIndexPath:indexPath];
  1392. PSTCollectionReusableView *view = _allVisibleViewsDict[key];
  1393. if (view) {
  1394. PSTCollectionViewLayoutAttributes *startAttrs = view.layoutAttributes;
  1395. if (!finalAttrs) {
  1396. finalAttrs = [startAttrs copy];
  1397. finalAttrs.alpha = 0;
  1398. }
  1399. [animations addObject:@{@"view" : view, @"previousLayoutInfos" : startAttrs, @"newLayoutInfos" : finalAttrs}];
  1400. [_allVisibleViewsDict removeObjectForKey:key];
  1401. [(NSMutableArray *)viewsToRemove[@(key.type)] addObject:view];
  1402. }
  1403. }
  1404. else if (updateItem.updateAction == PSTCollectionUpdateActionInsert) {
  1405. NSIndexPath *indexPath = updateItem.indexPathAfterUpdate;
  1406. PSTCollectionViewItemKey *key = [PSTCollectionViewItemKey collectionItemKeyForCellWithIndexPath:indexPath];
  1407. PSTCollectionViewLayoutAttributes *startAttrs = [_layout initialLayoutAttributesForAppearingItemAtIndexPath:indexPath];
  1408. PSTCollectionViewLayoutAttributes *finalAttrs = [_layout layoutAttributesForItemAtIndexPath:indexPath];
  1409. CGRect startRect = startAttrs.frame;
  1410. CGRect finalRect = finalAttrs.frame;
  1411. if (CGRectIntersectsRect(self.visibleBoundRects, startRect) || CGRectIntersectsRect(self.visibleBoundRects, finalRect)) {
  1412. if (!startAttrs) {
  1413. startAttrs = [finalAttrs copy];
  1414. startAttrs.alpha = 0;
  1415. }
  1416. PSTCollectionReusableView *view = [self createPreparedCellForItemAtIndexPath:indexPath
  1417. withLayoutAttributes:startAttrs];
  1418. [self addControlledSubview:view];
  1419. newAllVisibleView[key] = view;
  1420. [animations addObject:@{@"view" : view, @"previousLayoutInfos" : startAttrs, @"newLayoutInfos" : finalAttrs}];
  1421. }
  1422. }
  1423. else if (updateItem.updateAction == PSTCollectionUpdateActionMove) {
  1424. NSIndexPath *indexPathBefore = updateItem.indexPathBeforeUpdate;
  1425. NSIndexPath *indexPathAfter = updateItem.indexPathAfterUpdate;
  1426. PSTCollectionViewItemKey *keyBefore = [PSTCollectionViewItemKey collectionItemKeyForCellWithIndexPath:indexPathBefore];
  1427. PSTCollectionViewItemKey *keyAfter = [PSTCollectionViewItemKey collectionItemKeyForCellWithIndexPath:indexPathAfter];
  1428. PSTCollectionReusableView *view = _allVisibleViewsDict[keyBefore];
  1429. PSTCollectionViewLayoutAttributes *startAttrs = nil;
  1430. PSTCollectionViewLayoutAttributes *finalAttrs = [_layout layoutAttributesForItemAtIndexPath:indexPathAfter];
  1431. if (view) {
  1432. startAttrs = view.layoutAttributes;
  1433. [_allVisibleViewsDict removeObjectForKey:keyBefore];
  1434. newAllVisibleView[keyAfter] = view;
  1435. }
  1436. else {
  1437. startAttrs = [finalAttrs copy];
  1438. startAttrs.alpha = 0;
  1439. view = [self createPreparedCellForItemAtIndexPath:indexPathAfter withLayoutAttributes:startAttrs];
  1440. [self addControlledSubview:view];
  1441. newAllVisibleView[keyAfter] = view;
  1442. }
  1443. [animations addObject:@{@"view" : view, @"previousLayoutInfos" : startAttrs, @"newLayoutInfos" : finalAttrs}];
  1444. }
  1445. }
  1446. for (PSTCollectionViewItemKey *key in [_allVisibleViewsDict keyEnumerator]) {
  1447. PSTCollectionReusableView *view = _allVisibleViewsDict[key];
  1448. if (key.type == PSTCollectionViewItemTypeCell) {
  1449. NSUInteger oldGlobalIndex = [_update[@"oldModel"] globalIndexForItemAtIndexPath:key.indexPath];
  1450. NSArray *oldToNewIndexMap = _update[@"oldToNewIndexMap"];
  1451. NSUInteger newGlobalIndex = NSNotFound;
  1452. if (NSNotFound != oldGlobalIndex && oldGlobalIndex < oldToNewIndexMap.count) {
  1453. newGlobalIndex = [oldToNewIndexMap[oldGlobalIndex] intValue];
  1454. }
  1455. NSIndexPath *newIndexPath = newGlobalIndex == NSNotFound ? nil : [_update[@"newModel"] indexPathForItemAtGlobalIndex:newGlobalIndex];
  1456. NSIndexPath *oldIndexPath = oldGlobalIndex == NSNotFound ? nil : [_update[@"oldModel"] indexPathForItemAtGlobalIndex:oldGlobalIndex];
  1457. if (newIndexPath) {
  1458. PSTCollectionViewLayoutAttributes *startAttrs = nil;
  1459. PSTCollectionViewLayoutAttributes *finalAttrs = nil;
  1460. startAttrs = [_layout initialLayoutAttributesForAppearingItemAtIndexPath:oldIndexPath];
  1461. finalAttrs = [_layout layoutAttributesForItemAtIndexPath:newIndexPath];
  1462. NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"view" : view}];
  1463. if (startAttrs) dic[@"previousLayoutInfos"] = startAttrs;
  1464. if (finalAttrs) dic[@"newLayoutInfos"] = finalAttrs;
  1465. [animations addObject:dic];
  1466. PSTCollectionViewItemKey *newKey = [key copy];
  1467. [newKey setIndexPath:newIndexPath];
  1468. newAllVisibleView[newKey] = view;
  1469. }
  1470. }else if (key.type == PSTCollectionViewItemTypeSupplementaryView) {
  1471. PSTCollectionViewLayoutAttributes *startAttrs = nil;
  1472. PSTCollectionViewLayoutAttributes *finalAttrs = nil;
  1473. startAttrs = view.layoutAttributes;
  1474. finalAttrs = [_layout layoutAttributesForSupplementaryViewOfKind:view.layoutAttributes.representedElementKind atIndexPath:key.indexPath];
  1475. NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"view" : view}];
  1476. if (startAttrs) dic[@"previousLayoutInfos"] = startAttrs;
  1477. if (finalAttrs) dic[@"newLayoutInfos"] = finalAttrs;
  1478. [animations addObject:dic];
  1479. PSTCollectionViewItemKey *newKey = [key copy];
  1480. newAllVisibleView[newKey] = view;
  1481. }
  1482. }
  1483. NSArray *allNewlyVisibleItems = [_layout layoutAttributesForElementsInRect:self.visibleBoundRects];
  1484. for (PSTCollectionViewLayoutAttributes *attrs in allNewlyVisibleItems) {
  1485. PSTCollectionViewItemKey *key = [PSTCollectionViewItemKey collectionItemKeyForLayoutAttributes:attrs];
  1486. if (key.type == PSTCollectionViewItemTypeCell && ![[newAllVisibleView allKeys] containsObject:key]) {
  1487. PSTCollectionViewLayoutAttributes *startAttrs =
  1488. [_layout initialLayoutAttributesForAppearingItemAtIndexPath:attrs.indexPath];
  1489. PSTCollectionReusableView *view = [self createPreparedCellForItemAtIndexPath:attrs.indexPath
  1490. withLayoutAttributes:startAttrs];
  1491. [self addControlledSubview:view];
  1492. newAllVisibleView[key] = view;
  1493. [animations addObject:@{@"view" : view, @"previousLayoutInfos" : startAttrs ? startAttrs : attrs, @"newLayoutInfos" : attrs}];
  1494. }
  1495. }
  1496. _allVisibleViewsDict = newAllVisibleView;
  1497. for (NSDictionary *animation in animations) {
  1498. PSTCollectionReusableView *view = animation[@"view"];
  1499. PSTCollectionViewLayoutAttributes *attr = animation[@"previousLayoutInfos"];
  1500. [view applyLayoutAttributes:attr];
  1501. };
  1502. [UIView animateWithDuration:.3 animations:^{
  1503. self->_collectionViewFlags.updatingLayout = YES;
  1504. [CATransaction begin];
  1505. [CATransaction setAnimationDuration:.3];
  1506. // You might wonder why we use CATransaction to handle animation completion
  1507. // here instead of using the completion: parameter of UIView's animateWithDuration:.
  1508. // The problem is that animateWithDuration: calls this completion block
  1509. // when other animations are finished. This means that the block is called
  1510. // after the user releases his finger and the scroll view has finished scrolling.
  1511. // This can be a large delay, which causes the layout of the cells to be greatly
  1512. // delayed, and thus, be unrendered. I assume that was done for performance
  1513. // purposes but it completely breaks our layout logic here.
  1514. // To get the completion block called immediately after the animation actually
  1515. // finishes, I switched to use CATransaction.
  1516. // The only thing I'm not sure about - _completed_ flag. I don't know where to get it
  1517. // in terms of CATransaction's API, so I use animateWithDuration's completion block
  1518. // to call _updateCompletionHandler with that flag.
  1519. // Ideally, _updateCompletionHandler should be called along with the other logic in
  1520. // CATransaction's completionHandler but I simply don't know where to get that flag.
  1521. [CATransaction setCompletionBlock:^{
  1522. // Iterate through all the views that we are going to remove.
  1523. [viewsToRemove enumerateKeysAndObjectsUsingBlock:^(NSNumber *keyObj, NSArray *views, BOOL *stop) {
  1524. PSTCollectionViewItemType type = [keyObj unsignedIntegerValue];
  1525. for (PSTCollectionReusableView *view in views) {
  1526. if (type == PSTCollectionViewItemTypeCell) {
  1527. [self reuseCell:(PSTCollectionViewCell *)view];
  1528. }else if (type == PSTCollectionViewItemTypeSupplementaryView) {
  1529. [self reuseSupplementaryView:view];
  1530. }else if (type == PSTCollectionViewItemTypeDecorationView) {
  1531. [self reuseDecorationView:view];
  1532. }
  1533. }
  1534. }];
  1535. self->_collectionViewFlags.updatingLayout = NO;
  1536. }];
  1537. for (NSDictionary *animation in animations) {
  1538. PSTCollectionReusableView *view = animation[@"view"];
  1539. PSTCollectionViewLayoutAttributes *attrs = animation[@"newLayoutInfos"];
  1540. [view applyLayoutAttributes:attrs];
  1541. }
  1542. [CATransaction commit];
  1543. } completion:^(BOOL finished) {
  1544. if (self->_updateCompletionHandler) {
  1545. self->_updateCompletionHandler(finished);
  1546. self->_updateCompletionHandler = nil;
  1547. }
  1548. }];
  1549. [_layout finalizeCollectionViewUpdates];
  1550. }
  1551. - (void)setupCellAnimations {
  1552. [self updateVisibleCellsNow:YES];
  1553. [self suspendReloads];
  1554. _collectionViewFlags.updating = YES;
  1555. }
  1556. - (void)endItemAnimations {
  1557. _updateCount++;
  1558. PSTCollectionViewData *oldCollectionViewData = _collectionViewData;
  1559. _collectionViewData = [[PSTCollectionViewData alloc] initWithCollectionView:self layout:_layout];
  1560. [_layout invalidateLayout];
  1561. [_collectionViewData prepareToLoadData];
  1562. NSMutableArray *someMutableArr1 = [[NSMutableArray alloc] init];
  1563. NSArray *removeUpdateItems = [[self arrayForUpdateAction:PSTCollectionUpdateActionDelete]
  1564. sortedArrayUsingSelector:@selector(inverseCompareIndexPaths:)];
  1565. NSArray *insertUpdateItems = [[self arrayForUpdateAction:PSTCollectionUpdateActionInsert]
  1566. sortedArrayUsingSelector:@selector(compareIndexPaths:)];
  1567. NSMutableArray *sortedMutableReloadItems = [[_reloadItems sortedArrayUsingSelector:@selector(compareIndexPaths:)] mutableCopy];
  1568. NSMutableArray *sortedMutableMoveItems = [[_moveItems sortedArrayUsingSelector:@selector(compareIndexPaths:)] mutableCopy];
  1569. _originalDeleteItems = [removeUpdateItems copy];
  1570. _originalInsertItems = [insertUpdateItems copy];
  1571. NSMutableArray *someMutableArr2 = [[NSMutableArray alloc] init];
  1572. NSMutableArray *someMutableArr3 = [[NSMutableArray alloc] init];
  1573. NSMutableDictionary *operations = [[NSMutableDictionary alloc] init];
  1574. for (PSTCollectionViewUpdateItem *updateItem in sortedMutableReloadItems) {
  1575. NSAssert(updateItem.indexPathBeforeUpdate.section < [oldCollectionViewData numberOfSections],
  1576. @"attempt to reload item (%@) that doesn't exist (there are only %ld sections before update)",
  1577. updateItem.indexPathBeforeUpdate, (long)[oldCollectionViewData numberOfSections]);
  1578. if (updateItem.indexPathBeforeUpdate.item != NSNotFound) {
  1579. NSAssert(updateItem.indexPathBeforeUpdate.item < [oldCollectionViewData numberOfItemsInSection:updateItem.indexPathBeforeUpdate.section],
  1580. @"attempt to reload item (%@) that doesn't exist (there are only %ld items in section %ld before update)",
  1581. updateItem.indexPathBeforeUpdate,
  1582. (long)[oldCollectionViewData numberOfItemsInSection:updateItem.indexPathBeforeUpdate.section],
  1583. (long)updateItem.indexPathBeforeUpdate.section);
  1584. }
  1585. [someMutableArr2 addObject:[[PSTCollectionViewUpdateItem alloc] initWithAction:PSTCollectionUpdateActionDelete
  1586. forIndexPath:updateItem.indexPathBeforeUpdate]];
  1587. [someMutableArr3 addObject:[[PSTCollectionViewUpdateItem alloc] initWithAction:PSTCollectionUpdateActionInsert
  1588. forIndexPath:updateItem.indexPathAfterUpdate]];
  1589. }
  1590. NSMutableArray *sortedDeletedMutableItems = [[_deleteItems sortedArrayUsingSelector:@selector(inverseCompareIndexPaths:)] mutableCopy];
  1591. NSMutableArray *sortedInsertMutableItems = [[_insertItems sortedArrayUsingSelector:@selector(compareIndexPaths:)] mutableCopy];
  1592. for (PSTCollectionViewUpdateItem *deleteItem in sortedDeletedMutableItems) {
  1593. if ([deleteItem isSectionOperation]) {
  1594. NSAssert(deleteItem.indexPathBeforeUpdate.section < [oldCollectionViewData numberOfSections],
  1595. @"attempt to delete section (%ld) that doesn't exist (there are only %ld sections before update)",
  1596. (long)deleteItem.indexPathBeforeUpdate.section,
  1597. (long)[oldCollectionViewData numberOfSections]);
  1598. for (PSTCollectionViewUpdateItem *moveItem in sortedMutableMoveItems) {
  1599. if (moveItem.indexPathBeforeUpdate.section == deleteItem.indexPathBeforeUpdate.section) {
  1600. if (moveItem.isSectionOperation)
  1601. NSAssert(NO, @"attempt to delete and move from the same section %ld", (long)deleteItem.indexPathBeforeUpdate.section);
  1602. else
  1603. NSAssert(NO, @"attempt to delete and move from the same section (%@)", moveItem.indexPathBeforeUpdate);
  1604. }
  1605. }
  1606. }else {
  1607. NSAssert(deleteItem.indexPathBeforeUpdate.section < [oldCollectionViewData numberOfSections],
  1608. @"attempt to delete item (%@) that doesn't exist (there are only %ld sections before update)",
  1609. deleteItem.indexPathBeforeUpdate,
  1610. (long)[oldCollectionViewData numberOfSections]);
  1611. NSAssert(deleteItem.indexPathBeforeUpdate.item < [oldCollectionViewData numberOfItemsInSection:deleteItem.indexPathBeforeUpdate.section],
  1612. @"attempt to delete item (%@) that doesn't exist (there are only %ld items in section%ld before update)",
  1613. deleteItem.indexPathBeforeUpdate,
  1614. (long)[oldCollectionViewData numberOfItemsInSection:deleteItem.indexPathBeforeUpdate.section],
  1615. (long)deleteItem.indexPathBeforeUpdate.section);
  1616. for (PSTCollectionViewUpdateItem *moveItem in sortedMutableMoveItems) {
  1617. NSAssert(![deleteItem.indexPathBeforeUpdate isEqual:moveItem.indexPathBeforeUpdate],
  1618. @"attempt to delete and move the same item (%@)", deleteItem.indexPathBeforeUpdate);
  1619. }
  1620. if (!operations[@(deleteItem.indexPathBeforeUpdate.section)])
  1621. operations[@(deleteItem.indexPathBeforeUpdate.section)] = [NSMutableDictionary dictionary];
  1622. operations[@(deleteItem.indexPathBeforeUpdate.section)][@"deleted"] =
  1623. @([operations[@(deleteItem.indexPathBeforeUpdate.section)][@"deleted"] intValue] + 1);
  1624. }
  1625. }
  1626. for (NSUInteger i = 0; i < sortedInsertMutableItems.count; i++) {
  1627. PSTCollectionViewUpdateItem *insertItem = sortedInsertMutableItems[i];
  1628. NSIndexPath *indexPath = insertItem.indexPathAfterUpdate;
  1629. BOOL sectionOperation = [insertItem isSectionOperation];
  1630. if (sectionOperation) {
  1631. NSAssert([indexPath section] < [_collectionViewData numberOfSections],
  1632. @"attempt to insert %ld but there are only %ld sections after update",
  1633. (long)[indexPath section], (long)[_collectionViewData numberOfSections]);
  1634. for (PSTCollectionViewUpdateItem *moveItem in sortedMutableMoveItems) {
  1635. if ([moveItem.indexPathAfterUpdate isEqual:indexPath]) {
  1636. if (moveItem.isSectionOperation)
  1637. NSAssert(NO, @"attempt to perform an insert and a move to the same section (%ld)", (long)indexPath.section);
  1638. }
  1639. }
  1640. NSUInteger j = i + 1;
  1641. while (j < sortedInsertMutableItems.count) {
  1642. PSTCollectionViewUpdateItem *nextInsertItem = sortedInsertMutableItems[j];
  1643. if (nextInsertItem.indexPathAfterUpdate.section == indexPath.section) {
  1644. NSAssert(nextInsertItem.indexPathAfterUpdate.item < [_collectionViewData numberOfItemsInSection:indexPath.section],
  1645. @"attempt to insert item %ld into section %ld, but there are only %ld items in section %ld after the update",
  1646. (long)nextInsertItem.indexPathAfterUpdate.item,
  1647. (long)indexPath.section,
  1648. (long)[_collectionViewData numberOfItemsInSection:indexPath.section],
  1649. (long)indexPath.section);
  1650. [sortedInsertMutableItems removeObjectAtIndex:j];
  1651. }
  1652. else break;
  1653. }
  1654. }else {
  1655. NSAssert(indexPath.item < [_collectionViewData numberOfItemsInSection:indexPath.section],
  1656. @"attempt to insert item to (%@) but there are only %ld items in section %ld after update",
  1657. indexPath,
  1658. (long)[_collectionViewData numberOfItemsInSection:indexPath.section],
  1659. (long)indexPath.section);
  1660. if (!operations[@(indexPath.section)])
  1661. operations[@(indexPath.section)] = [NSMutableDictionary dictionary];
  1662. operations[@(indexPath.section)][@"inserted"] =
  1663. @([operations[@(indexPath.section)][@"inserted"] intValue] + 1);
  1664. }
  1665. }
  1666. for (PSTCollectionViewUpdateItem *sortedItem in sortedMutableMoveItems) {
  1667. if (sortedItem.isSectionOperation) {
  1668. NSAssert(sortedItem.indexPathBeforeUpdate.section < [oldCollectionViewData numberOfSections],
  1669. @"attempt to move section (%ld) that doesn't exist (%ld sections before update)",
  1670. (long)sortedItem.indexPathBeforeUpdate.section,
  1671. (long)[oldCollectionViewData numberOfSections]);
  1672. NSAssert(sortedItem.indexPathAfterUpdate.section < [_collectionViewData numberOfSections],
  1673. @"attempt to move section to %ld but there are only %ld sections after update",
  1674. (long)sortedItem.indexPathAfterUpdate.section,
  1675. (long)[_collectionViewData numberOfSections]);
  1676. }else {
  1677. NSAssert(sortedItem.indexPathBeforeUpdate.section < [oldCollectionViewData numberOfSections],
  1678. @"attempt to move item (%@) that doesn't exist (%ld sections before update)",
  1679. sortedItem, (long)[oldCollectionViewData numberOfSections]);
  1680. NSAssert(sortedItem.indexPathBeforeUpdate.item < [oldCollectionViewData numberOfItemsInSection:sortedItem.indexPathBeforeUpdate.section],
  1681. @"attempt to move item (%@) that doesn't exist (%ld items in section %ld before update)",
  1682. sortedItem,
  1683. (long)[oldCollectionViewData numberOfItemsInSection:sortedItem.indexPathBeforeUpdate.section],
  1684. (long)sortedItem.indexPathBeforeUpdate.section);
  1685. NSAssert(sortedItem.indexPathAfterUpdate.section < [_collectionViewData numberOfSections],
  1686. @"attempt to move item to (%@) but there are only %ld sections after update",
  1687. sortedItem.indexPathAfterUpdate,
  1688. (long)[_collectionViewData numberOfSections]);
  1689. NSAssert(sortedItem.indexPathAfterUpdate.item < [_collectionViewData numberOfItemsInSection:sortedItem.indexPathAfterUpdate.section],
  1690. @"attempt to move item to (%@) but there are only %ld items in section %ld after update",
  1691. sortedItem,
  1692. (long)[_collectionViewData numberOfItemsInSection:sortedItem.indexPathAfterUpdate.section],
  1693. (long)sortedItem.indexPathAfterUpdate.section);
  1694. }
  1695. if (!operations[@(sortedItem.indexPathBeforeUpdate.section)])
  1696. operations[@(sortedItem.indexPathBeforeUpdate.section)] = [NSMutableDictionary dictionary];
  1697. if (!operations[@(sortedItem.indexPathAfterUpdate.section)])
  1698. operations[@(sortedItem.indexPathAfterUpdate.section)] = [NSMutableDictionary dictionary];
  1699. operations[@(sortedItem.indexPathBeforeUpdate.section)][@"movedOut"] =
  1700. @([operations[@(sortedItem.indexPathBeforeUpdate.section)][@"movedOut"] intValue] + 1);
  1701. operations[@(sortedItem.indexPathAfterUpdate.section)][@"movedIn"] =
  1702. @([operations[@(sortedItem.indexPathAfterUpdate.section)][@"movedIn"] intValue] + 1);
  1703. }
  1704. #if !defined NS_BLOCK_ASSERTIONS
  1705. for (NSNumber *sectionKey in [operations keyEnumerator]) {
  1706. NSInteger section = [sectionKey intValue];
  1707. NSInteger insertedCount = [operations[sectionKey][@"inserted"] intValue];
  1708. NSInteger deletedCount = [operations[sectionKey][@"deleted"] intValue];
  1709. NSInteger movedInCount = [operations[sectionKey][@"movedIn"] intValue];
  1710. NSInteger movedOutCount = [operations[sectionKey][@"movedOut"] intValue];
  1711. NSAssert([oldCollectionViewData numberOfItemsInSection:section] + insertedCount - deletedCount + movedInCount - movedOutCount ==
  1712. [_collectionViewData numberOfItemsInSection:section],
  1713. @"invalid update in section %ld: number of items after update (%ld) should be equal to the number of items before update (%ld) "\
  1714. "plus count of inserted items (%ld), minus count of deleted items (%ld), plus count of items moved in (%ld), minus count of items moved out (%ld)",
  1715. (long)section,
  1716. (long)[_collectionViewData numberOfItemsInSection:section],
  1717. (long)[oldCollectionViewData numberOfItemsInSection:section],
  1718. (long)insertedCount, (long)deletedCount, (long)movedInCount, (long)movedOutCount);
  1719. }
  1720. #endif
  1721. [someMutableArr2 addObjectsFromArray:sortedDeletedMutableItems];
  1722. [someMutableArr3 addObjectsFromArray:sortedInsertMutableItems];
  1723. [someMutableArr1 addObjectsFromArray:[someMutableArr2 sortedArrayUsingSelector:@selector(inverseCompareIndexPaths:)]];
  1724. [someMutableArr1 addObjectsFromArray:sortedMutableMoveItems];
  1725. [someMutableArr1 addObjectsFromArray:[someMutableArr3 sortedArrayUsingSelector:@selector(compareIndexPaths:)]];
  1726. NSMutableArray *layoutUpdateItems = [[NSMutableArray alloc] init];
  1727. [layoutUpdateItems addObjectsFromArray:sortedDeletedMutableItems];
  1728. [layoutUpdateItems addObjectsFromArray:sortedMutableMoveItems];
  1729. [layoutUpdateItems addObjectsFromArray:sortedInsertMutableItems];
  1730. NSMutableArray *newModel = [NSMutableArray array];
  1731. for (NSInteger i = 0; i < [oldCollectionViewData numberOfSections]; i++) {
  1732. NSMutableArray *sectionArr = [NSMutableArray array];
  1733. for (NSInteger j = 0; j < [oldCollectionViewData numberOfItemsInSection:i]; j++)
  1734. [sectionArr addObject:@([oldCollectionViewData globalIndexForItemAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i]])];
  1735. [newModel addObject:sectionArr];
  1736. }
  1737. for (PSTCollectionViewUpdateItem *updateItem in layoutUpdateItems) {
  1738. switch (updateItem.updateAction) {
  1739. case PSTCollectionUpdateActionDelete: {
  1740. if (updateItem.isSectionOperation) {
  1741. // section updates are ignored anyway in animation code. If not commented, mixing rows and section deletion causes crash in else below
  1742. // [newModel removeObjectAtIndex:updateItem.indexPathBeforeUpdate.section];
  1743. }else {
  1744. [(NSMutableArray *)newModel[updateItem.indexPathBeforeUpdate.section]
  1745. removeObjectAtIndex:updateItem.indexPathBeforeUpdate.item];
  1746. }
  1747. }
  1748. break;
  1749. case PSTCollectionUpdateActionInsert: {
  1750. if (updateItem.isSectionOperation) {
  1751. [newModel insertObject:[[NSMutableArray alloc] init]
  1752. atIndex:updateItem.indexPathAfterUpdate.section];
  1753. }else {
  1754. [(NSMutableArray *)newModel[updateItem.indexPathAfterUpdate.section]
  1755. insertObject:@(NSNotFound)
  1756. atIndex:updateItem.indexPathAfterUpdate.item];
  1757. }
  1758. }
  1759. break;
  1760. case PSTCollectionUpdateActionMove: {
  1761. if (updateItem.isSectionOperation) {
  1762. id section = newModel[updateItem.indexPathBeforeUpdate.section];
  1763. [newModel insertObject:section atIndex:updateItem.indexPathAfterUpdate.section];
  1764. }
  1765. else {
  1766. id object = @([oldCollectionViewData globalIndexForItemAtIndexPath:updateItem.indexPathBeforeUpdate]);
  1767. [newModel[updateItem.indexPathBeforeUpdate.section] removeObject:object];
  1768. [newModel[updateItem.indexPathAfterUpdate.section] insertObject:object
  1769. atIndex:updateItem.indexPathAfterUpdate.item];
  1770. }
  1771. }
  1772. break;
  1773. default: break;
  1774. }
  1775. }
  1776. NSMutableArray *oldToNewMap = [NSMutableArray arrayWithCapacity:[oldCollectionViewData numberOfItems]];
  1777. NSMutableArray *newToOldMap = [NSMutableArray arrayWithCapacity:[_collectionViewData numberOfItems]];
  1778. for (NSInteger i = 0; i < [oldCollectionViewData numberOfItems]; i++)
  1779. [oldToNewMap addObject:@(NSNotFound)];
  1780. for (NSInteger i = 0; i < [_collectionViewData numberOfItems]; i++)
  1781. [newToOldMap addObject:@(NSNotFound)];
  1782. for (NSUInteger i = 0; i < newModel.count; i++) {
  1783. NSMutableArray *section = newModel[i];
  1784. for (NSUInteger j = 0; j < section.count; j++) {
  1785. NSInteger newGlobalIndex = [_collectionViewData globalIndexForItemAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i]];
  1786. if ([section[j] integerValue] != NSNotFound)
  1787. oldToNewMap[[section[j] intValue]] = @(newGlobalIndex);
  1788. if (newGlobalIndex != NSNotFound)
  1789. newToOldMap[newGlobalIndex] = section[j];
  1790. }
  1791. }
  1792. _update = @{@"oldModel" : oldCollectionViewData, @"newModel" : _collectionViewData, @"oldToNewIndexMap" : oldToNewMap, @"newToOldIndexMap" : newToOldMap};
  1793. [self updateWithItems:someMutableArr1];
  1794. _originalInsertItems = nil;
  1795. _originalDeleteItems = nil;
  1796. _insertItems = nil;
  1797. _deleteItems = nil;
  1798. _moveItems = nil;
  1799. _reloadItems = nil;
  1800. _update = nil;
  1801. _updateCount--;
  1802. _collectionViewFlags.updating = NO;
  1803. [self resumeReloads];
  1804. }
  1805. - (void)updateRowsAtIndexPaths:(NSArray *)indexPaths updateAction:(PSTCollectionUpdateAction)updateAction {
  1806. BOOL updating = _collectionViewFlags.updating;
  1807. if (!updating) [self setupCellAnimations];
  1808. NSMutableArray *array = [self arrayForUpdateAction:updateAction]; //returns appropriate empty array if not exists
  1809. for (NSIndexPath *indexPath in indexPaths) {
  1810. PSTCollectionViewUpdateItem *updateItem = [[PSTCollectionViewUpdateItem alloc] initWithAction:updateAction forIndexPath:indexPath];
  1811. [array addObject:updateItem];
  1812. }
  1813. if (!updating) [self endItemAnimations];
  1814. }
  1815. - (void)updateSections:(NSIndexSet *)sections updateAction:(PSTCollectionUpdateAction)updateAction {
  1816. BOOL updating = _collectionViewFlags.updating;
  1817. if (!updating) [self setupCellAnimations];
  1818. NSMutableArray *updateActions = [self arrayForUpdateAction:updateAction];
  1819. [sections enumerateIndexesUsingBlock:^(NSUInteger section, BOOL *stop) {
  1820. PSTCollectionViewUpdateItem *updateItem = [[PSTCollectionViewUpdateItem alloc] initWithAction:updateAction forIndexPath:[NSIndexPath indexPathForItem:NSNotFound inSection:section]];
  1821. [updateActions addObject:updateItem];
  1822. }];
  1823. if (!updating) [self endItemAnimations];
  1824. }
  1825. ///////////////////////////////////////////////////////////////////////////////////////////
  1826. #pragma mark - PSTCollection/UICollection interoperability
  1827. #ifdef kPSUIInteroperabilityEnabled
  1828. #import <objc/message.h>
  1829. - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
  1830. NSMethodSignature *sig = [super methodSignatureForSelector:selector];
  1831. if(!sig) {
  1832. NSString *selString = NSStringFromSelector(selector);
  1833. if ([selString hasPrefix:@"_"]) {
  1834. SEL cleanedSelector = NSSelectorFromString([selString substringFromIndex:1]);
  1835. sig = [super methodSignatureForSelector:cleanedSelector];
  1836. }
  1837. }
  1838. return sig;
  1839. }
  1840. - (void)forwardInvocation:(NSInvocation *)inv {
  1841. NSString *selString = NSStringFromSelector([inv selector]);
  1842. if ([selString hasPrefix:@"_"]) {
  1843. SEL cleanedSelector = NSSelectorFromString([selString substringFromIndex:1]);
  1844. if ([self respondsToSelector:cleanedSelector]) {
  1845. // dynamically add method for faster resolving
  1846. Method newMethod = class_getInstanceMethod(self.class, [inv selector]);
  1847. IMP underscoreIMP = imp_implementationWithBlock(^(id _self) {
  1848. return objc_msgSend(_self, cleanedSelector);
  1849. });
  1850. class_addMethod(self.class, [inv selector], underscoreIMP, method_getTypeEncoding(newMethod));
  1851. // invoke now
  1852. inv.selector = cleanedSelector;
  1853. [inv invokeWithTarget:self];
  1854. }
  1855. }else {
  1856. [super forwardInvocation:inv];
  1857. }
  1858. }
  1859. #endif
  1860. @end
  1861. ///////////////////////////////////////////////////////////////////////////////////////////
  1862. #pragma mark - Runtime Additions to create UICollectionView
  1863. @implementation PSUICollectionView_ @end
  1864. @implementation PSUICollectionViewCell_ @end
  1865. @implementation PSUICollectionReusableView_ @end
  1866. @implementation PSUICollectionViewLayout_ @end
  1867. @implementation PSUICollectionViewFlowLayout_ @end
  1868. @implementation PSUICollectionViewLayoutAttributes_ @end
  1869. @implementation PSUICollectionViewController_ @end
  1870. static BOOL PSTRegisterClass(NSString *UIClassName, Class PSTClass) {
  1871. NSCParameterAssert(UIClassName && PSTClass);
  1872. Class UIClass = NSClassFromString(UIClassName);
  1873. if (UIClass) {
  1874. // Class size need to be the same for class_setSuperclass to work.
  1875. // If the UIKit class is smaller then our subclass, ivars won't clash, so there's no issue.
  1876. long sizeDifference = class_getInstanceSize(UIClass) - class_getInstanceSize(PSTClass);
  1877. if (sizeDifference > 0) {
  1878. NSLog(@"Warning! ivar size mismatch in %@ - can't change the superclass.", PSTClass);
  1879. return NO;
  1880. } else {
  1881. #pragma clang diagnostic push
  1882. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1883. // class_setSuperclass is deprecated, but still exists and works on iOS6/7.
  1884. class_setSuperclass(PSTClass, UIClass);
  1885. #pragma clang diagnostic pop
  1886. }
  1887. } else {
  1888. // We're most likely on iOS5, the requested UIKit class doesn't exist, so we create it dynamically.
  1889. if ((UIClass = objc_allocateClassPair(PSTClass, UIClassName.UTF8String, 0))) {
  1890. objc_registerClassPair(UIClass);
  1891. }
  1892. }
  1893. return YES;
  1894. }
  1895. // Create subclasses that pose as UICollectionView et al, if not available at runtime.
  1896. __attribute__((constructor)) static void PSTCreateUICollectionViewClasses(void) {
  1897. if (objc_getClass("PSTCollectionViewDisableForwardToUICollectionViewSentinel")) return;
  1898. @autoreleasepool {
  1899. // Change superclass at runtime. This allows seamless switching from PST* to UI* at runtime.
  1900. PSTRegisterClass(@"UICollectionView", PSUICollectionView_.class);
  1901. PSTRegisterClass(@"UICollectionViewCell", PSUICollectionViewCell_.class);
  1902. PSTRegisterClass(@"UICollectionReusableView", PSUICollectionReusableView_.class);
  1903. PSTRegisterClass(@"UICollectionViewLayout", PSUICollectionViewLayout_.class);
  1904. PSTRegisterClass(@"UICollectionViewFlowLayout", PSUICollectionViewFlowLayout_.class);
  1905. PSTRegisterClass(@"UICollectionViewLayoutAttributes", PSUICollectionViewLayoutAttributes_.class);
  1906. PSTRegisterClass(@"UICollectionViewController", PSUICollectionViewController_.class);
  1907. // add PSUI classes at runtime to make Interface Builder sane
  1908. // (IB doesn't allow adding the PSUICollectionView_ types but doesn't complain on unknown classes)
  1909. // The class name may already be in use. This may happen if this code is running for the second time (first for an app bundle, then again for a unit test bundle).
  1910. Class c;
  1911. if ((c = objc_allocateClassPair(PSUICollectionView_.class, "PSUICollectionView", 0))) objc_registerClassPair(c);
  1912. if ((c = objc_allocateClassPair(PSUICollectionViewCell_.class, "PSUICollectionViewCell", 0))) objc_registerClassPair(c);
  1913. if ((c = objc_allocateClassPair(PSUICollectionReusableView_.class, "PSUICollectionReusableView", 0))) objc_registerClassPair(c);
  1914. if ((c = objc_allocateClassPair(PSUICollectionViewLayout_.class, "PSUICollectionViewLayout", 0))) objc_registerClassPair(c);
  1915. if ((c = objc_allocateClassPair(PSUICollectionViewFlowLayout_.class, "PSUICollectionViewFlowLayout", 0))) objc_registerClassPair(c);
  1916. if ((c = objc_allocateClassPair(PSUICollectionViewLayoutAttributes_.class, "PSUICollectionViewLayoutAttributes", 0)))objc_registerClassPair(c);
  1917. if ((c = objc_allocateClassPair(PSUICollectionViewController_.class, "PSUICollectionViewController", 0))) objc_registerClassPair(c);
  1918. }
  1919. }
  1920. CGFloat PSTSimulatorAnimationDragCoefficient(void) {
  1921. static CGFloat (*UIAnimationDragCoefficient)(void) = NULL;
  1922. #if TARGET_IPHONE_SIMULATOR
  1923. static dispatch_once_t onceToken;
  1924. dispatch_once(&onceToken, ^{
  1925. UIAnimationDragCoefficient = (CGFloat (*)(void))dlsym(RTLD_DEFAULT, "UIAnimationDragCoefficient");
  1926. });
  1927. #endif
  1928. return UIAnimationDragCoefficient ? UIAnimationDragCoefficient() : 1.f;
  1929. }
  1930. // helper to check for ivar layout
  1931. #if 0
  1932. static void PSTPrintIvarsForClass(Class aClass) {
  1933. unsigned int varCount;
  1934. Ivar *vars = class_copyIvarList(aClass, &varCount);
  1935. for (int i = 0; i < varCount; i++) {
  1936. NSLog(@"%s %s", ivar_getTypeEncoding(vars[i]), ivar_getName(vars[i]));
  1937. }
  1938. free(vars);
  1939. }
  1940. __attribute__((constructor)) static void PSTCheckIfIVarLayoutIsEqualSize(void) {
  1941. @autoreleasepool {
  1942. NSLog(@"PSTCollectionView size = %zd, UICollectionView size = %zd", class_getInstanceSize(PSTCollectionView.class),class_getInstanceSize(UICollectionView.class));
  1943. NSLog(@"PSTCollectionViewCell size = %zd, UICollectionViewCell size = %zd", class_getInstanceSize(PSTCollectionViewCell.class),class_getInstanceSize(UICollectionViewCell.class));
  1944. NSLog(@"PSTCollectionViewController size = %zd, UICollectionViewController size = %zd", class_getInstanceSize(PSTCollectionViewController.class),class_getInstanceSize(UICollectionViewController.class));
  1945. NSLog(@"PSTCollectionViewLayout size = %zd, UICollectionViewLayout size = %zd", class_getInstanceSize(PSTCollectionViewLayout.class),class_getInstanceSize(UICollectionViewLayout.class));
  1946. NSLog(@"PSTCollectionViewFlowLayout size = %zd, UICollectionViewFlowLayout size = %zd", class_getInstanceSize(PSTCollectionViewFlowLayout.class),class_getInstanceSize(UICollectionViewFlowLayout.class));
  1947. //PSTPrintIvarsForClass(PSTCollectionViewFlowLayout.class); NSLog(@"\n\n\n");PSTPrintIvarsForClass(UICollectionViewFlowLayout.class);
  1948. }
  1949. }
  1950. #endif