-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathMGCTimedEventsViewLayout.m
executable file
·478 lines (375 loc) · 17.7 KB
/
MGCTimedEventsViewLayout.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//
// MGCTimedEventsViewLayout.m
// Graphical Calendars Library for iOS
//
// Distributed under the MIT License
// Get the latest version from here:
//
// https://github.com/jumartin/Calendar
//
// Copyright (c) 2014-2015 Julien Martin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#import "MGCTimedEventsViewLayout.h"
#import "MGCEventCellLayoutAttributes.h"
#import "MGCAlignedGeometry.h"
// In iOS 8.1.2 and older, there is a bug with UICollectionView that will make
// cells disappear when their frame overlap vertically the visible rect (i.e the one passed in
// layoutAttributesForElementsInRect:)
// To avoid this, we constraint the height of the cells frame so that they entirely fit in the rect.
// Then we have to remember to invalidate the whole layout whenever this visible rect changes
// see http://stackoverflow.com/questions/13770484/large-uicollectionviewcells-disappearing-with-custom-layout
// or https://github.com/mattjgalloway/CocoaBugs/blob/master/UICollectionView-MissingCells/README.md
//#define BUG_FIX // cannot reproduce this bug anymore
static NSString* const DimmingViewsKey = @"DimmingViewsKey";
static NSString* const EventCellsKey = @"EventCellsKey";
@implementation MGCTimedEventsViewLayoutInvalidationContext
- (instancetype)init {
if (self = [super init]) {
self.invalidateDimmingViews = NO;
self.invalidateEventCells = YES;
}
return self;
}
@end
@interface MGCTimedEventsViewLayout()
@property (nonatomic) NSMutableDictionary *layoutInfo;
#ifdef BUG_FIX
@property (nonatomic) CGRect visibleBounds;
@property (nonatomic) BOOL shouldInvalidate;
#endif
@end
@implementation MGCTimedEventsViewLayout
- (instancetype)init {
if (self = [super init]) {
_minimumVisibleHeight = 15.;
_ignoreNextInvalidation = NO;
}
return self;
}
- (NSMutableDictionary*)layoutInfo
{
if (!_layoutInfo) {
NSInteger numSections = self.collectionView.numberOfSections;
_layoutInfo = [NSMutableDictionary dictionaryWithCapacity:numSections];
}
return _layoutInfo;
}
- (NSArray*)layoutAttributesForDimmingViewsInSection:(NSUInteger)section
{
NSArray *dimmingRects = [self.delegate collectionView:self.collectionView layout:self dimmingRectsForSection:section];
NSMutableArray *layoutAttribs = [NSMutableArray arrayWithCapacity:dimmingRects.count];
for (NSInteger item = 0; item < dimmingRects.count; item++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
CGRect rect = [dimmingRects[item] CGRectValue];
if (!CGRectIsNull(rect)) {
UICollectionViewLayoutAttributes *viewAttribs = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:DimmingViewKind withIndexPath:indexPath];
rect.origin.x = self.dayColumnSize.width * indexPath.section;
rect.size.width = self.dayColumnSize.width;
viewAttribs.frame = MGCAlignedRect(rect);
[layoutAttribs addObject:viewAttribs];
}
}
return layoutAttribs;
}
- (NSArray*)layoutAttributesForEventCellsInSection:(NSUInteger)section
{
NSInteger numItems = [self.collectionView numberOfItemsInSection:section];
NSMutableArray *layoutAttribs = [NSMutableArray arrayWithCapacity:numItems];
for (NSInteger item = 0; item < numItems; item++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
CGRect rect = [self.delegate collectionView:self.collectionView layout:self rectForEventAtIndexPath:indexPath];
if (!CGRectIsNull(rect)) {
MGCEventCellLayoutAttributes *cellAttribs = [MGCEventCellLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
rect.origin.x = self.dayColumnSize.width * indexPath.section;
rect.size.width = self.dayColumnSize.width;
rect.size.height = fmax(self.minimumVisibleHeight, rect.size.height);
cellAttribs.frame = MGCAlignedRect(CGRectInset(rect , 0, 1));
cellAttribs.visibleHeight = cellAttribs.frame.size.height;
cellAttribs.zIndex = 1; // should appear above dimming views
[layoutAttribs addObject:cellAttribs];
}
}
return [self adjustLayoutForOverlappingCells:layoutAttribs inSection:section];
}
- (NSDictionary*)layoutAttributesForSection:(NSUInteger)section
{
NSMutableDictionary *sectionAttribs = [self.layoutInfo objectForKey:@(section)];
if (!sectionAttribs) {
sectionAttribs = [NSMutableDictionary dictionary];
}
if (![sectionAttribs objectForKey:DimmingViewsKey]) {
NSArray *dimmingViewsAttribs = [self layoutAttributesForDimmingViewsInSection:section];
[sectionAttribs setObject:dimmingViewsAttribs forKey:DimmingViewsKey];
}
if (![sectionAttribs objectForKey:EventCellsKey]) {
NSArray *cellsAttribs = [self layoutAttributesForEventCellsInSection:section];
[sectionAttribs setObject:cellsAttribs forKey:EventCellsKey];
}
[self.layoutInfo setObject:sectionAttribs forKey:@(section)];
return sectionAttribs;
}
- (NSArray*)adjustLayoutForOverlappingCells:(NSArray*)attributes inSection:(NSUInteger)section
{
const CGFloat kOverlapOffset = 4.;
// sort layout attributes by frame y-position
NSArray *adjustedAttributes = [attributes sortedArrayUsingComparator:^NSComparisonResult(MGCEventCellLayoutAttributes *att1, MGCEventCellLayoutAttributes *att2) {
if (att1.frame.origin.y > att2.frame.origin.y) {
return NSOrderedDescending;
}
else if (att1.frame.origin.y < att2.frame.origin.y) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
if (self.coveringType == TimedEventCoveringTypeClassic) {
for (NSUInteger i = 0; i < adjustedAttributes.count; i++) {
MGCEventCellLayoutAttributes *attribs1 = [adjustedAttributes objectAtIndex:i];
NSMutableArray *layoutGroup = [NSMutableArray array];
[layoutGroup addObject:attribs1];
NSMutableArray *coveredLayoutAttributes = [NSMutableArray array];
// iterate previous frames (i.e with highest or equal y-pos)
for (NSInteger j = i - 1; j >= 0; j--) {
MGCEventCellLayoutAttributes *attribs2 = [adjustedAttributes objectAtIndex:j];
if (CGRectIntersectsRect(attribs1.frame, attribs2.frame)) {
CGFloat visibleHeight = fabs(attribs1.frame.origin.y - attribs2.frame.origin.y);
if (visibleHeight > self.minimumVisibleHeight) {
[coveredLayoutAttributes addObject:attribs2];
attribs2.visibleHeight = visibleHeight;
attribs1.zIndex = attribs2.zIndex + 1;
}
else {
[layoutGroup addObject:attribs2];
}
}
}
// now, distribute elements in layout group
CGFloat groupOffset = 0;
if (coveredLayoutAttributes.count > 0) {
BOOL lookForEmptySlot = YES;
NSUInteger slotNumber = 0;
CGFloat offset = 0;
while (lookForEmptySlot) {
offset = slotNumber * kOverlapOffset;
lookForEmptySlot = NO;
for (MGCEventCellLayoutAttributes *attribs in coveredLayoutAttributes) {
if (attribs.frame.origin.x - section * self.dayColumnSize.width == offset) {
lookForEmptySlot = YES;
break;
}
}
slotNumber += 1;
}
groupOffset += offset;
}
CGFloat totalWidth = (self.dayColumnSize.width - 1.) - groupOffset;
CGFloat colWidth = totalWidth / layoutGroup.count;
CGFloat x = section * self.dayColumnSize.width + groupOffset;
for (MGCEventCellLayoutAttributes* attribs in [layoutGroup reverseObjectEnumerator]) {
attribs.frame = MGCAlignedRectMake(x, attribs.frame.origin.y, colWidth, attribs.frame.size.height);
x += colWidth;
}
}
return adjustedAttributes;
} else if (self.coveringType == TimedEventCoveringTypeComplex) {
// Create clusters - groups of rectangles which don't have common parts with other groups
NSMutableArray *uninspectedAttributes = [adjustedAttributes mutableCopy];
NSMutableArray<NSMutableArray<MGCEventCellLayoutAttributes *> *> *clusters = [NSMutableArray new];
while (uninspectedAttributes.count > 0) {
MGCEventCellLayoutAttributes *attrib = [uninspectedAttributes firstObject];
NSMutableArray<MGCEventCellLayoutAttributes *> *destinationCluster;
for (NSMutableArray<MGCEventCellLayoutAttributes *> *cluster in clusters) {
for (MGCEventCellLayoutAttributes *clusteredAttrib in cluster) {
if (CGRectIntersectsRect(clusteredAttrib.frame, attrib.frame)) {
destinationCluster = cluster;
break;
}
}
}
if (destinationCluster) {
[destinationCluster addObject:attrib];
} else {
NSMutableArray<MGCEventCellLayoutAttributes *> *cluster = [NSMutableArray new];
[cluster addObject:attrib];
[clusters addObject:cluster];
}
[uninspectedAttributes removeObject:attrib];
}
// Distribute rectangles evenly in clusters
for (NSMutableArray<MGCEventCellLayoutAttributes *> *cluster in clusters) {
[self expandCellsToMaxWidthInCluster:cluster];
}
// Gather all the attributes and return them
NSMutableArray *attributes = [NSMutableArray new];
for (NSMutableArray<MGCEventCellLayoutAttributes *> *cluster in clusters) {
[attributes addObjectsFromArray:cluster];
}
return attributes;
}
return @[];
}
- (void)expandCellsToMaxWidthInCluster:(NSMutableArray<MGCEventCellLayoutAttributes *> *)cluster
{
const NSUInteger padding = 2.f;
// Expand the attributes to maximum possible width
NSMutableArray<NSMutableArray<MGCEventCellLayoutAttributes *> *> *columns = [NSMutableArray new];
[columns addObject:[NSMutableArray new]];
for (MGCEventCellLayoutAttributes *attribs in cluster) {
BOOL isPlaced = NO;
for (NSMutableArray<MGCEventCellLayoutAttributes *> *column in columns) {
if (column.count == 0) {
[column addObject:attribs];
isPlaced = YES;
} else if (!CGRectIntersectsRect(attribs.frame, [column lastObject].frame)) {
[column addObject:attribs];
isPlaced = YES;
break;
}
}
if (!isPlaced) {
NSMutableArray<MGCEventCellLayoutAttributes *> *column = [NSMutableArray new];
[column addObject:attribs];
[columns addObject:column];
}
}
// Calculate left and right position for all the attributes, get the maxRowCount by looking in all columns
NSInteger maxRowCount = 0;
for (NSMutableArray<MGCEventCellLayoutAttributes *> *column in columns) {
maxRowCount = fmax(maxRowCount, column.count);
}
CGFloat totalWidth = self.dayColumnSize.width - 2.f;
for (NSInteger i = 0; i < maxRowCount; i++) {
// Set the x position of the rect
NSInteger j = 0;
for (NSMutableArray<MGCEventCellLayoutAttributes *> *column in columns) {
CGFloat colWidth = totalWidth / columns.count;
if (column.count >= i + 1) {
MGCEventCellLayoutAttributes *attribs = [column objectAtIndex:i];
attribs.frame = MGCAlignedRectMake(attribs.frame.origin.x + j * colWidth,
attribs.frame.origin.y,
colWidth,
attribs.frame.size.height);
}
j++;
}
}
}
#pragma mark - UICollectionViewLayout
+ (Class)layoutAttributesClass
{
return [MGCEventCellLayoutAttributes class];
}
+ (Class)invalidationContextClass
{
return [MGCTimedEventsViewLayoutInvalidationContext class];
}
- (MGCEventCellLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath*)indexPath
{
//NSLog(@"layoutAttributesForItemAtIndexPath %@", indexPath);
NSArray *attribs = [[self layoutAttributesForSection:indexPath.section] objectForKey:EventCellsKey];
return [attribs objectAtIndex:indexPath.item];
}
- (UICollectionViewLayoutAttributes*)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
NSArray *attribs = [[self layoutAttributesForSection:indexPath.section] objectForKey:DimmingViewsKey];
return [attribs objectAtIndex:indexPath.item];
}
- (void)prepareForCollectionViewUpdates:(NSArray*)updateItems
{
//NSLog(@"prepare Collection updates");
[super prepareForCollectionViewUpdates:updateItems];
}
- (void)invalidateLayoutWithContext:(MGCTimedEventsViewLayoutInvalidationContext *)context
{
//NSLog(@"invalidateLayoutWithContext");
[super invalidateLayoutWithContext:context];
if (self.ignoreNextInvalidation) {
self.ignoreNextInvalidation = NO;
return;
}
if (context.invalidateEverything || context.invalidatedSections == nil) {
self.layoutInfo = nil;
}
else {
[context.invalidatedSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
if (context.invalidateDimmingViews) {
[[self.layoutInfo objectForKey:@(idx)]removeObjectForKey:DimmingViewsKey];
}
if (context.invalidateEventCells) {
[[self.layoutInfo objectForKey:@(idx)]removeObjectForKey:EventCellsKey];
}
}];
}
}
- (void)invalidateLayout
{
//NSLog(@"invalidateLayout");
[super invalidateLayout];
}
- (CGSize)collectionViewContentSize
{
return CGSizeMake(self.dayColumnSize.width * self.collectionView.numberOfSections, self.dayColumnSize.height);
}
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
//NSLog(@"layoutAttributesForElementsInRect %@", NSStringFromCGRect(rect));
#ifdef BUG_FIX
self.shouldInvalidate = self.visibleBounds.origin.y != rect.origin.y || self.visibleBounds.size.height != rect.size.height;
//self.shouldInvalidate = !CGRectEqualToRect(self.visibleBounds, rect);
self.visibleBounds = rect;
#endif
NSMutableArray *allAttribs = [NSMutableArray array];
// determine first and last day intersecting rect
NSUInteger maxSection = self.collectionView.numberOfSections;
NSUInteger first = MAX(0, floorf(rect.origin.x / self.dayColumnSize.width));
NSUInteger last = MIN(MAX(first, ceilf(CGRectGetMaxX(rect) / self.dayColumnSize.width)), maxSection);
for (NSInteger day = first; day < last; day++) {
NSDictionary *layoutDic = [self layoutAttributesForSection:day];
NSArray *attribs = [[layoutDic objectForKey:DimmingViewsKey]arrayByAddingObjectsFromArray:[layoutDic objectForKey:EventCellsKey]];
for (UICollectionViewLayoutAttributes *a in attribs) {
if (CGRectIntersectsRect(rect, a.frame)) {
#ifdef BUG_FIX
CGRect frame = a.frame;
frame.size.height = fminf(frame.size.height, CGRectGetMaxY(rect) - frame.origin.y);
a.frame = frame;
#endif
[allAttribs addObject:a];
}
}
}
return allAttribs;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
//NSLog(@"shouldInvalidateLayoutForBoundsChange %@", NSStringFromCGRect(newBounds));
CGRect oldBounds = self.collectionView.bounds;
return
#ifdef BUG_FIX
self.shouldInvalidate ||
#endif
oldBounds.size.width != newBounds.size.width;
}
// we keep this for iOS 8 compatibility. As of iOS 9, this is replaced by collectionView:targetContentOffsetForProposedContentOffset:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
{
id<UICollectionViewDelegate> delegate = (id<UICollectionViewDelegate>)self.collectionView.delegate;
return [delegate collectionView:self.collectionView targetContentOffsetForProposedContentOffset:proposedContentOffset];
}
@end