forked from steipete/PSStackedView
/
PSStackedViewController.m
1421 lines (1172 loc) · 57.1 KB
/
PSStackedViewController.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// SVStackRootController.m
// PSStackedView
//
// Created by Peter Steinberger on 7/14/11.
// Copyright 2011 Peter Steinberger. All rights reserved.
//
#import "PSStackedView.h"
#import "UIViewController+PSStackedView.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>
#define kPSSVStackAnimationSpeedModifier 1.f // DEBUG!
#define kPSSVStackAnimationDuration kPSSVStackAnimationSpeedModifier * 0.25f
#define kPSSVStackAnimationBounceDuration kPSSVStackAnimationSpeedModifier * 0.20f
#define kPSSVStackAnimationPushDuration kPSSVStackAnimationSpeedModifier * 0.25f
#define kPSSVStackAnimationPopDuration kPSSVStackAnimationSpeedModifier * 0.25f
#define kPSSVMaxSnapOverOffset 20
#define kPSSVAssociatedBaseViewControllerKey @"kPSSVAssociatedBaseViewController"
// reduces alpha over overlapped view controllers. 1.f would totally black-out on complete overlay
#define kAlphaReductRatio 2.f
#define EPSILON .001f // float calculations
// prevents me getting crazy
typedef void(^PSSVSimpleBlock)(void);
@interface PSStackedViewController() <UIGestureRecognizerDelegate>
@property(nonatomic, retain) UIViewController *rootViewController;
@property(nonatomic, assign) NSMutableArray* viewControllers;
@property(nonatomic, assign) NSInteger firstVisibleIndex;
@property(nonatomic, assign) CGFloat floatIndex;
- (UIViewController *)overlappedViewController;
@end
@implementation PSStackedViewController
@synthesize leftInset = leftInset_;
@synthesize largeLeftInset = largeLeftInset_;
@synthesize viewControllers = viewControllers_;
@synthesize floatIndex = floatIndex_;
@synthesize rootViewController = rootViewController_;
@synthesize panRecognizer = panRecognizer_;
@synthesize delegate = delegate_;
@synthesize reduceAnimations = reduceAnimations_;
@dynamic firstVisibleIndex;
#ifdef ALLOW_SWIZZLING_NAVIGATIONCONTROLLER
@synthesize navigationBar;
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - NSObject
- (id)initWithRootViewController:(UIViewController *)rootViewController; {
if ((self = [super init])) {
rootViewController_ = [rootViewController retain];
viewControllers_ = [[NSMutableArray alloc] init];
// set some reasonble defaults
leftInset_ = 60;
largeLeftInset_ = 200;
// add a gesture recognizer to detect dragging to the guest controllers
UIPanGestureRecognizer *panRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)] autorelease];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelaysTouchesBegan:NO];
[panRecognizer setDelaysTouchesEnded:YES];
[panRecognizer setCancelsTouchesInView:YES];
panRecognizer.delegate = self;
[self.view addGestureRecognizer:panRecognizer];
self.panRecognizer = panRecognizer;
#ifdef ALLOW_SWIZZLING_NAVIGATIONCONTROLLER
PSSVLog("Swizzling UIViewController.navigationController");
Method origMethod = class_getInstanceMethod([UIViewController class], @selector(navigationController));
Method overrideMethod = class_getInstanceMethod([UIViewController class], @selector(navigationControllerSwizzled));
method_exchangeImplementations(origMethod, overrideMethod);
#endif
}
return self;
}
- (void)dealloc {
delegate_ = nil;
panRecognizer_.delegate = nil;
// remove all view controllers the hard way (w/o calling delegate)
while ([self.viewControllers count]) {
[self popViewControllerAnimated:NO];
}
[panRecognizer_ release];
[rootViewController_ release];
[viewControllers_ release];
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Delegate
- (void)setDelegate:(id<PSStackedViewDelegate>)delegate {
if (delegate != delegate_) {
delegate_ = delegate;
delegateFlags_.delegateWillInsertViewController = [delegate respondsToSelector:@selector(stackedView:willInsertViewController:)];
delegateFlags_.delegateDidInsertViewController = [delegate respondsToSelector:@selector(stackedView:didInsertViewController:)];
delegateFlags_.delegateWillRemoveViewController = [delegate respondsToSelector:@selector(stackedView:willRemoveViewController:)];
delegateFlags_.delegateDidRemoveViewController = [delegate respondsToSelector:@selector(stackedView:didRemoveViewController:)];
}
}
- (void)delegateWillInsertViewController:(UIViewController *)viewController {
if (delegateFlags_.delegateWillInsertViewController) {
[self.delegate stackedView:self willInsertViewController:viewController];
}
}
- (void)delegateDidInsertViewController:(UIViewController *)viewController {
if (delegateFlags_.delegateDidInsertViewController) {
[self.delegate stackedView:self didInsertViewController:viewController];
}
}
- (void)delegateWillRemoveViewController:(UIViewController *)viewController {
if (delegateFlags_.delegateWillRemoveViewController) {
[self.delegate stackedView:self willRemoveViewController:viewController];
}
}
- (void)delegateDidRemoveViewController:(UIViewController *)viewController {
if (delegateFlags_.delegateDidRemoveViewController) {
[self.delegate stackedView:self didRemoveViewController:viewController];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private Helpers
- (NSInteger)firstVisibleIndex {
NSInteger firstVisibleIndex = floorf(self.floatIndex);
return firstVisibleIndex;
}
- (CGRect)viewRect {
// self.view.frame not used, it's wrong in viewWillAppear
CGRect viewRect = [[UIScreen mainScreen] applicationFrame];
return viewRect;
}
// return screen width
- (CGFloat)screenWidth {
CGRect viewRect = [self viewRect];
CGFloat screenWidth = PSIsLandscape() ? viewRect.size.height : viewRect.size.width;
return screenWidth;
}
- (CGFloat)screenHeight {
CGRect viewRect = [self viewRect];
NSUInteger screenHeight = PSIsLandscape() ? viewRect.size.width : viewRect.size.height;
return screenHeight;
}
- (CGFloat)maxControllerWidth {
CGFloat maxWidth = [self screenWidth] - self.leftInset;
return maxWidth;
}
// total stack width if completely expanded
- (NSUInteger)totalStackWidth {
NSUInteger totalStackWidth = 0;
for (UIViewController *controller in self.viewControllers) {
totalStackWidth += controller.containerView.width;
}
return totalStackWidth;
}
// menu is only collapsable if stack is large enough
- (BOOL)isMenuCollapsable {
BOOL isMenuCollapsable = [self totalStackWidth] + self.largeLeftInset > [self screenWidth];
return isMenuCollapsable;
}
// return current left border (how it *should* be)
- (NSUInteger)currentLeftInset {
return self.floatIndex >= 0.5 ? self.leftInset : self.largeLeftInset;
}
// minimal left border is depending on amount of VCs
- (NSUInteger)minimalLeftInset {
return [self isMenuCollapsable] ? self.leftInset : self.largeLeftInset;
}
// check if a view controller is visible or not
- (BOOL)isViewControllerVisible:(UIViewController *)viewController completely:(BOOL)completely {
NSParameterAssert(viewController);
NSUInteger screenWidth = [self screenWidth];
BOOL isVCVisible = ((viewController.containerView.left < screenWidth && !completely) ||
(completely && viewController.containerView.right <= screenWidth));
return isVCVisible;
}
// returns view controller that is displayed before viewController
- (UIViewController *)previousViewController:(UIViewController *)viewController {
if(!viewController) // don't assert on mere menu events
return nil;
NSUInteger vcIndex = [self indexOfViewController:viewController];
UIViewController *prevVC = nil;
if (vcIndex > 0) {
prevVC = [self.viewControllers objectAtIndex:vcIndex-1];
}
return prevVC;
}
// returns view controller that is displayed after viewController
- (UIViewController *)nextViewController:(UIViewController *)viewController {
NSParameterAssert(viewController);
NSUInteger vcIndex = [self indexOfViewController:viewController];
UIViewController *nextVC = nil;
if (vcIndex + 1 < [self.viewControllers count]) {
nextVC = [self.viewControllers objectAtIndex:vcIndex+1];
}
return nextVC;
}
// returns last visible view controller. this *can* be the last view controller in the stack,
// but also one of the previous ones if the user navigates back in the stack
- (UIViewController *)lastVisibleViewControllerCompletelyVisible:(BOOL)completely {
__block UIViewController *lastVisibleViewController = nil;
[self.viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *currentViewController = (UIViewController *)obj;
if ([self isViewControllerVisible:currentViewController completely:completely]) {
lastVisibleViewController = currentViewController;
*stop = YES;
}
}];
return lastVisibleViewController;
}
// returns true if firstVisibleIndex is the last available index.
- (BOOL)isLastIndex {
BOOL isLastIndex = self.firstVisibleIndex == [self.viewControllers count] - 1;
return isLastIndex;
}
enum {
PSSVRoundNearest,
PSSVRoundUp,
PSSVRoundDown
}typedef PSSVRoundOption;
- (BOOL)isFloatIndexBetween:(CGFloat)floatIndex {
CGFloat intIndex, restIndex;
restIndex = modff(floatIndex, &intIndex);
BOOL isBetween = fabsf(restIndex - 0.5f) < EPSILON;
return isBetween;
}
// check if index is valid. Valid indexes are >= 0.0 and only full or .5 parts are allowed.
// there are lots of other, more complex rules, so calculate!
- (BOOL)isValidFloatIndex:(CGFloat)floatIndex {
BOOL isValid = floatIndex == 0.f; // 0.f is always allowed
if (!isValid) {
CGFloat contentWidth = [self totalStackWidth];
if (floatIndex == 0.5f) {
// docking to menu is only allowed if content > available size.
isValid = contentWidth > [self screenWidth] - self.largeLeftInset;
}else {
NSUInteger stackCount = [self.viewControllers count];
CGFloat intIndex, restIndex;
restIndex = modff(floatIndex, &intIndex); // split e.g. 1.5 in 1.0 and 0.5
isValid = stackCount > intIndex && contentWidth > ([self screenWidth] - self.leftInset);
if (isValid && fabsf(restIndex - 0.5f) < EPSILON) { // comparing floats -> if so, we have a .5 here
if (ceilf(floatIndex) < stackCount) { // at the end?
CGFloat widthLeft = [[self.viewControllers objectAtIndex:floorf(floatIndex)] containerView].width;
CGFloat widthRight = [[self.viewControllers objectAtIndex:ceilf(floatIndex)] containerView].width;
isValid = (widthLeft + widthRight) > ([self screenWidth] - self.leftInset);
}else {
isValid = NO;
}
}
}
}
return isValid;
}
- (CGFloat)nearestValidFloatIndex:(CGFloat)floatIndex round:(PSSVRoundOption)roundOption {
CGFloat roundedFloat;
CGFloat intIndex, restIndex;
restIndex = modff(floatIndex, &intIndex);
if (restIndex < 0.5f) {
if (roundOption == PSSVRoundNearest) {
restIndex = (restIndex < 0.25f) ? 0.f : 0.5f;
}else {
restIndex = (roundOption == PSSVRoundUp) ? 0.5f : 0.f;
}
}else {
if (roundOption == PSSVRoundNearest) {
restIndex = (restIndex < 0.75f) ? 0.5f : 1.f;
}else {
restIndex = (roundOption == PSSVRoundUp) ? 1.f : 0.5f;
}
}
roundedFloat = intIndex + restIndex;
// now check if this is valid
BOOL isValid = [self isValidFloatIndex:roundedFloat];
// if not valid, and custom rounding produced a .5, test again with full rounding
if (!isValid && restIndex == 0.5f) {
CGFloat naturalRoundedIndex;
if (roundOption == PSSVRoundNearest) {
naturalRoundedIndex = roundf(floatIndex);
}else if(roundOption == PSSVRoundUp) {
naturalRoundedIndex = ceilf(floatIndex);
}else {
naturalRoundedIndex = floorf(floatIndex);
}
// if that works out, return it!
if ([self isValidFloatIndex:naturalRoundedIndex]) {
isValid = YES;
roundedFloat = naturalRoundedIndex;
}
}
// still not valid? start the for loops, find nearest valid index
if (!isValid) {
CGFloat validLowIndex = 0.f, validHighIndex = 0.f;
// upper bound
CGFloat viewControllerCount = [self.viewControllers count];
for (CGFloat tester = roundedFloat + 0.5f; tester < viewControllerCount; tester += 0.5f) {
if ([self isValidFloatIndex:tester]) {
validHighIndex = tester;
break;
}
}
// lower bound
for (CGFloat tester = roundedFloat - 0.5f; tester >= 0.f; tester -= 0.5f) {
if ([self isValidFloatIndex:tester]) {
validLowIndex = tester;
break;
}
}
if (fabsf(validLowIndex - roundedFloat) < fabsf(validHighIndex - roundedFloat)) {
roundedFloat = validLowIndex;
}else {
roundedFloat = validHighIndex;
}
}
return roundedFloat;
}
- (CGFloat)nearestValidFloatIndex:(CGFloat)floatIndex {
return [self nearestValidFloatIndex:floatIndex round:PSSVRoundNearest];
}
- (CGFloat)nextFloatIndex:(CGFloat)floatIndex {
CGFloat nextFloat = 0.f;
CGFloat roundedFloat = [self nearestValidFloatIndex:floatIndex];
CGFloat viewControllerCount = [self.viewControllers count];
for (CGFloat tester = roundedFloat + 0.5f; tester < viewControllerCount; tester += 0.5f) {
if ([self isValidFloatIndex:tester]) {
nextFloat = tester;
break;
}
}
return nextFloat;
}
- (CGFloat)prevFloatIndex:(CGFloat)floatIndex {
CGFloat prevFloat = 0.f;
CGFloat roundedFloat = [self nearestValidFloatIndex:floatIndex];
for (CGFloat tester = roundedFloat - 0.5f; tester >= 0.f; tester -= 0.5f) {
if ([self isValidFloatIndex:tester]) {
prevFloat = tester;
break;
}
}
return prevFloat;
}
/// calculates all rects for current visibleIndex orientation
- (NSArray *)rectsForControllers {
NSMutableArray *frames = [NSMutableArray array];
// TODO: currently calculates *all* objects, should cache!
CGFloat floatIndex = [self nearestValidFloatIndex:self.floatIndex];
[self.viewControllers enumerateObjectsWithOptions:0 usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *currentVC = (UIViewController *)obj;
CGFloat leftPos = [self currentLeftInset];
CGRect leftRect = idx > 0 ? [[frames objectAtIndex:idx-1] CGRectValue] : CGRectZero;
if (idx == floorf(floatIndex)) {
BOOL dockRight = ![self isFloatIndexBetween:floatIndex] && floatIndex >= 1.f;
// should we pan it to the right?
if (dockRight) {
leftPos = [self screenWidth] - currentVC.containerView.width;
}
}else if (idx > floatIndex) {
// connect vc to left vc's right!
leftPos = leftRect.origin.x + leftRect.size.width;
}
CGRect currentRect = CGRectMake(leftPos, currentVC.containerView.top, currentVC.containerView.width, currentVC.containerView.height);
[frames addObject:[NSValue valueWithCGRect:currentRect]];
}];
return frames;
}
/// calculates the specific rect
- (CGRect)rectForControllerAtIndex:(NSUInteger)index {
NSArray *frames = [self rectsForControllers];
return [[frames objectAtIndex:index] CGRectValue];
}
/// moves a rect around, recalculates following rects
- (NSArray *)modifiedRects:(NSArray *)frames newLeft:(CGFloat)newLeft index:(NSUInteger)index {
NSMutableArray *modifiedFrames = [NSMutableArray arrayWithArray:frames];
CGRect prevFrame;
for (int i = index; i < [modifiedFrames count]; i++) {
CGRect vcFrame = [[modifiedFrames objectAtIndex:i] CGRectValue];
if (i == index) {
vcFrame.origin.x = newLeft;
}else {
vcFrame.origin.x = prevFrame.origin.x + prevFrame.size.width;
}
[modifiedFrames replaceObjectAtIndex:i withObject:[NSValue valueWithCGRect:vcFrame]];
prevFrame = vcFrame;
}
return modifiedFrames;
}
// at some point, dragging does not make any more sense
- (BOOL)snapPointAvailableAfterOffset:(NSInteger)offset {
BOOL snapPointAvailableAfterOffset = YES;
NSUInteger screenWidth = [self screenWidth];
NSUInteger totalWidth = [self totalStackWidth];
NSUInteger minCommonWidth = MIN(screenWidth, totalWidth);
// NSArray *frames = [self rectsForControllers];
// are we at the end?
UIViewController *topViewController = [self topViewController];
if (topViewController == [self lastVisibleViewControllerCompletelyVisible:YES]) {
if (minCommonWidth + [self minimalLeftInset] <= topViewController.containerView.right) {
snapPointAvailableAfterOffset = NO;
}
}
// slow down first controller when dragged to the right
if ([self canCollapseStack] == 0) {
snapPointAvailableAfterOffset = NO;
}
if ([self firstViewController].containerView.left > self.largeLeftInset) {
snapPointAvailableAfterOffset = NO;
}
return snapPointAvailableAfterOffset;
}
- (BOOL)displayViewControllerOnRightMost:(UIViewController *)vc animated:(BOOL)animated {
NSUInteger index = [self indexOfViewController:vc];
if (index != NSNotFound) {
[self displayViewControllerIndexOnRightMost:index animated:animated];
return YES;
}
return NO;
}
// ensures index is on rightmost position
- (void)displayViewControllerIndexOnRightMost:(NSInteger)index animated:(BOOL)animated; {
// add epsilon to round indexes like 1.0 to 2.0, also -1.0 to -2.0
CGFloat floatIndexOffset = index - self.floatIndex;
NSInteger indexOffset = ceilf(floatIndexOffset + (floatIndexOffset > 0 ? EPSILON : -EPSILON));
if (indexOffset > 0) {
[self collapseStack:indexOffset animated:animated];
}else if(indexOffset < 0) {
[self expandStack:indexOffset animated:animated];
}
// hide menu, if first VC is larger than available screen space with floatIndex = 0.0
else if (index == 0 && [self.viewControllers count] && [[self.viewControllers objectAtIndex:0] containerView].width >= ([self screenWidth] - self.leftInset)) {
self.floatIndex = 0.5f;
[self alignStackAnimated:YES];
}
}
// iterates controllers and sets width (also, enlarges if requested width is larger than current width)
- (void)updateViewControllerSizes {
CGFloat maxControllerView = [self maxControllerWidth];
for (UIViewController *controller in self.viewControllers) {
[controller.containerView limitToMaxWidth:maxControllerView];
}
}
- (CGFloat)overlapRatio {
CGFloat overlapRatio = 0.f;
UIViewController *overlappedVC = [self overlappedViewController];
if (overlappedVC) {
UIViewController *rightVC = [self nextViewController:overlappedVC];
PSSVLog(@"overlapping %@ with %@", NSStringFromCGRect(overlappedVC.containerView.frame), NSStringFromCGRect(rightVC.containerView.frame));
overlapRatio = fabsf(overlappedVC.containerView.right - rightVC.containerView.left)/overlappedVC.containerView.width;
}
return overlapRatio;
}
// updates view containers
- (void)updateViewControllerMasksAndShadow {
// only one!
if ([self.viewControllers count] == 1) {
// [[self firstViewController].containerView addMaskToCorners:UIRectCornerAllCorners];
self.firstViewController.containerView.shadow = PSSVSideLeft | PSSVSideRight;
}else {
// rounded corners on first and last controller
[self.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *vc = (UIViewController *)obj;
if (idx == 0) {
//[vc.containerView addMaskToCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft];
}else if(idx == [self.viewControllers count]-1) {
// [vc.containerView addMaskToCorners:UIRectCornerBottomRight | UIRectCornerTopRight];
vc.containerView.shadow = PSSVSideLeft | PSSVSideRight;
}else {
// [vc.containerView removeMask];
vc.containerView.shadow = PSSVSideLeft | PSSVSideRight;
}
}];
}
// update alpha mask
CGFloat overlapRatio = [self overlapRatio];
UIViewController *overlappedVC = [self overlappedViewController];
overlappedVC.containerView.darkRatio = MIN(overlapRatio, 1.f)/kAlphaReductRatio;
// reset alpha ratio everywhere else
for (UIViewController *vc in self.viewControllers) {
if (vc != overlappedVC) {
vc.containerView.darkRatio = 0.0f;
}
}
}
- (NSArray *)visibleViewControllersSetFullyVisible:(BOOL)fullyVisible; {
NSMutableArray *array = [NSMutableArray array];
[self.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([self isViewControllerVisible:obj completely:fullyVisible]) {
[array addObject:obj];
}
}];
return [[array copy] autorelease];
}
// check if there is any overlapping going on between VCs
- (BOOL)isViewController:(UIViewController *)leftViewController overlappingWith:(UIViewController *)rightViewController {
NSParameterAssert(leftViewController);
NSParameterAssert(rightViewController);
// figure out which controller is the top one
if ([self indexOfViewController:rightViewController] < [self indexOfViewController:leftViewController]) {
PSSVLog(@"overlapping check flipped! fixing that...");
UIViewController *tmp = rightViewController;
rightViewController = leftViewController;
leftViewController = tmp;
}
BOOL overlapping = leftViewController.containerView.right > rightViewController.containerView.left;
if (overlapping) {
PSSVLog(@"overlap detected: %@ (%@) with %@ (%@)", leftViewController, NSStringFromCGRect(leftViewController.containerView.frame), rightViewController, NSStringFromCGRect(rightViewController.containerView.frame));
}
return overlapping;
}
// find the rightmost overlapping controller
- (UIViewController *)overlappedViewController {
__block UIViewController *overlappedViewController = nil;
[self.viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *currentViewController = (UIViewController *)obj;
UIViewController *leftViewController = [self previousViewController:currentViewController];
BOOL overlapping = NO;
if (leftViewController && currentViewController) {
overlapping = [self isViewController:leftViewController overlappingWith:currentViewController];
}
if (overlapping) {
overlappedViewController = leftViewController;
*stop = YES;
}
}];
return overlappedViewController;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Touch Handling
- (void)stopStackAnimation {
// remove all current animations
//[self.view.layer removeAllAnimations];
[self.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *vc = (UIViewController *)obj;
[vc.containerView.layer removeAllAnimations];
}];
}
// moves the stack to a specific offset.
- (void)moveStackWithOffset:(NSInteger)offset animated:(BOOL)animated userDragging:(BOOL)userDragging {
PSSVLog(@"moving stack on %d pixels (animated:%d, decellerating:%d)", offset, animated, userDragging);
[self stopStackAnimation];
[UIView animateWithDuration:animated ? kPSSVStackAnimationDuration : 0.f delay:0.f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction animations:^{
// enumerate controllers from rig ht to left
// scroll each controller until we begin to overlap!
__block BOOL isTopViewController = YES;
[self.viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *currentViewController = (UIViewController *)obj;
UIViewController *leftViewController = [self previousViewController:currentViewController];
UIViewController *rightViewController = [self nextViewController:currentViewController];
NSInteger minimalLeftInset = [self minimalLeftInset];
// we just move the top view controller
NSInteger currentVCLeftPosition = currentViewController.containerView.left;
if (isTopViewController) {
currentVCLeftPosition += offset;
}else {
// make sure we're connected to the next controller!
currentVCLeftPosition = rightViewController.containerView.left - currentViewController.containerView.width;
}
// prevent scrolling < minimal width (except for the top view controller - allow stupidness!)
if (currentVCLeftPosition < minimalLeftInset && (!userDragging || (userDragging && !isTopViewController))) {
currentVCLeftPosition = minimalLeftInset;
}
// a previous view controller is not allowed to overlap the next view controller.
if (leftViewController && leftViewController.containerView.right > currentVCLeftPosition) {
NSInteger leftVCLeftPosition = currentVCLeftPosition - leftViewController.containerView.width;
if (leftVCLeftPosition < minimalLeftInset) {
leftVCLeftPosition = minimalLeftInset;
}
leftViewController.containerView.left = leftVCLeftPosition;
}
currentViewController.containerView.left = currentVCLeftPosition;
isTopViewController = NO; // there can only be one.
}];
[self updateViewControllerMasksAndShadow];
// special case, if we have overlapping controllers!
// in this case underlying controllers are visible, but they are overlapped by another controller
UIViewController *lastViewController = [self lastVisibleViewControllerCompletelyVisible:YES];
// there may be no controller completely visible - use partly visible then
if (!lastViewController) {
NSArray *visibleViewControllers = self.visibleViewControllers;
lastViewController = [visibleViewControllers count] ? [visibleViewControllers objectAtIndex:0] : nil;
}
// calculate float index
NSUInteger newFirstVisibleIndex = lastViewController ? [self indexOfViewController:lastViewController] : 0;
CGFloat floatIndex = [self nearestValidFloatIndex:newFirstVisibleIndex]; // absolut value
CGFloat overlapRatio = 0.f;
UIViewController *overlappedVC = [self overlappedViewController];
if (overlappedVC) {
UIViewController *rightVC = [self nextViewController:overlappedVC];
PSSVLog(@"overlapping %@ with %@", NSStringFromCGRect(overlappedVC.containerView.frame), NSStringFromCGRect(rightVC.containerView.frame));
overlapRatio = fabsf(overlappedVC.containerView.right - rightVC.containerView.left)/(overlappedVC.containerView.right - ([self screenWidth] - rightVC.containerView.width));
}
// only update ratio if < 1 (else we move sth else)
if (overlapRatio <= 1.f && overlapRatio > 0.f) {
floatIndex += 0.5f + overlapRatio*0.5f; // fully overlapped = the .5 ratio!
}else {
// overlap ratio
UIViewController *lastVC = [self.visibleViewControllers lastObject];
UIViewController *prevVC = [self previousViewController:lastVC];
if (lastVC && prevVC && lastVC.containerView.right > [self screenWidth]) {
overlapRatio = fabsf(([self screenWidth] - lastVC.containerView.left)/([self screenWidth] - (self.leftInset + prevVC.containerView.width)))*.5f;
floatIndex += overlapRatio;
}
}
// special case for menu
if (floatIndex == 0.f) {
CGFloat menuCollapsedRatio = (self.largeLeftInset - self.firstViewController.containerView.left)/(self.largeLeftInset - self.leftInset);
menuCollapsedRatio = MAX(0.0f, MIN(0.5f, menuCollapsedRatio/2));
floatIndex += menuCollapsedRatio;
}
floatIndex_ = floatIndex;
} completion:nil];
}
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
CGPoint translatedPoint = [recognizer translationInView:self.view];
UIGestureRecognizerState state = recognizer.state;
// reset last offset if gesture just started
if (state == UIGestureRecognizerStateBegan) {
lastDragOffset_ = 0;
}
NSInteger offset = translatedPoint.x - lastDragOffset_;
// if the move does not make sense (no snapping region), only use 1/2 offset
BOOL snapPointAvailable = [self snapPointAvailableAfterOffset:offset];
if (!snapPointAvailable) {
PSSVLog(@"offset dividing/2 in effect");
// we only want to move full pixels - but if we drag slowly, 1 get divided to zero.
// so only omit every second event
if (abs(offset) == 1) {
if(!lastDragDividedOne_) {
lastDragDividedOne_ = YES;
offset = 0;
}else {
lastDragDividedOne_ = NO;
}
}else {
offset = roundf(offset/2.f);
}
}
[self moveStackWithOffset:offset animated:NO userDragging:YES];
// set up designated drag destination
if (state == UIGestureRecognizerStateBegan) {
if (offset > 0) {
lastDragOption_ = SVSnapOptionRight;
}else {
lastDragOption_ = SVSnapOptionLeft;
}
}else {
// if there's a continuous drag in one direction, keep designation - else use nearest to snap.
if ((lastDragOption_ == SVSnapOptionLeft && offset > 0) || (lastDragOption_ == SVSnapOptionRight && offset < 0)) {
lastDragOption_ = SVSnapOptionNearest;
}
}
// save last point to calculate new offset
if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged) {
lastDragOffset_ = translatedPoint.x;
}
// perform snapping after gesture ended
BOOL gestureEnded = state == UIGestureRecognizerStateEnded;
if (gestureEnded) {
if (lastDragOption_ == SVSnapOptionRight) {
self.floatIndex = [self nearestValidFloatIndex:self.floatIndex round:PSSVRoundDown];
}else if(lastDragOption_ == SVSnapOptionLeft) {
self.floatIndex = [self nearestValidFloatIndex:self.floatIndex round:PSSVRoundUp];
}else {
self.floatIndex = [self nearestValidFloatIndex:self.floatIndex round:PSSVRoundNearest];
}
[self alignStackAnimated:YES];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - SVStackRootController (Public)
- (NSInteger)indexOfViewController:(UIViewController *)viewController {
__block NSUInteger index = [self.viewControllers indexOfObject:viewController];
if (index == NSNotFound) {
index = [self.viewControllers indexOfObject:viewController.navigationController];
if (index == NSNotFound) {
[self.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[UINavigationController class]] && ((UINavigationController *)obj).topViewController == viewController) {
index = idx;
*stop = YES;
}
}];
}
}
return index;
}
- (UIViewController *)topViewController {
return [self.viewControllers lastObject];
}
- (UIViewController *)firstViewController {
return [self.viewControllers count] ? [self.viewControllers objectAtIndex:0] : nil;
}
- (NSArray *)visibleViewControllers {
return [self visibleViewControllersSetFullyVisible:NO];
}
- (NSArray *)fullyVisibleViewControllers {
return [self visibleViewControllersSetFullyVisible:YES];
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated; {
[self pushViewController:viewController fromViewController:self.topViewController animated:animated];
}
- (void)pushViewController:(UIViewController *)viewController fromViewController:(UIViewController *)baseViewController animated:(BOOL)animated; {
// figure out where to push, and if we need to get rid of some viewControllers
if (baseViewController) {
[self.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIViewController *baseVC = objc_getAssociatedObject(obj, kPSSVAssociatedBaseViewControllerKey);
if (baseVC == baseViewController) {
PSSVLog(@"BaseViewController found on index: %d", idx);
UIViewController *parentVC = [self previousViewController:obj];
if (parentVC) {
[self popToViewController:parentVC animated:animated];
}else {
[self popToRootViewControllerAnimated:animated];
}
*stop = YES;
}
}];
objc_setAssociatedObject(viewController, kPSSVAssociatedBaseViewControllerKey, baseViewController, OBJC_ASSOCIATION_ASSIGN); // associate weak
}
PSSVLog(@"pushing with index %d on stack: %@ (animated: %d)", [self.viewControllers count], viewController, animated);
viewController.view.height = [self screenHeight];
// get predefined stack width; query topViewController if we have a UINavigationController
CGFloat stackWidth = viewController.stackWidth;
if (stackWidth == 0.f && [viewController isKindOfClass:[UINavigationController class]]) {
UIViewController *topVC = ((UINavigationController *)viewController).topViewController;
stackWidth = topVC.stackWidth;
}
if (stackWidth > 0.f) {
viewController.view.width = stackWidth;
}
// Starting out in portrait, right side up, we see a 20 pixel gap (for status bar???)
viewController.view.top = 0.f;
[self delegateWillInsertViewController:viewController];
// controller view is embedded into a container
PSSVContainerView *container = [PSSVContainerView containerViewWithController:viewController];
NSUInteger leftGap = [self totalStackWidth] + [self minimalLeftInset];
container.left = leftGap;
container.width = viewController.view.width;
container.autoresizingMask = UIViewAutoresizingFlexibleHeight; // width is not flexible!
[container limitToMaxWidth:[self maxControllerWidth]];
PSSVLog(@"container frame: %@", NSStringFromCGRect(container.frame));
// relay willAppear and add to subview
[viewController viewWillAppear:animated];
if (animated) {
container.alpha = 0.f;
container.transform = CGAffineTransformMakeScale(1.2, 1.2); // large but fade in
}
[self.view addSubview:container];
if (animated) {
[UIView animateWithDuration:kPSSVStackAnimationPushDuration delay:0.f options:UIViewAnimationOptionAllowUserInteraction animations:^{
container.alpha = 1.f;
container.transform = CGAffineTransformIdentity;
} completion:nil];
}
// properly sizes the scroll view contents (for table view scrolling)
[container layoutIfNeeded];
//container.width = viewController.view.width; // sync width (after it may has changed in layoutIfNeeded)
[viewController viewDidAppear:animated];
[viewControllers_ addObject:viewController];
// register stack controller
objc_setAssociatedObject(viewController, kPSSVAssociatedStackViewControllerKey, self, OBJC_ASSOCIATION_ASSIGN);
[self updateViewControllerMasksAndShadow];
[self displayViewControllerIndexOnRightMost:[self.viewControllers count]-1 animated:animated];
[self delegateDidInsertViewController:viewController];
}
- (BOOL)popViewController:(UIViewController *)controller animated:(BOOL)animated {
if (controller != self.topViewController) {
return NO;
}else {
return [self popViewControllerAnimated:animated] == controller;
}
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated; {
PSSVLog(@"popping controller: %@ (#%d total, animated:%d)", [self topViewController], [self.viewControllers count], animated);
UIViewController *lastController = [self topViewController];
if (lastController) {
[self delegateWillRemoveViewController:lastController];
// remove from view stack!
PSSVContainerView *container = lastController.containerView;
[lastController viewWillDisappear:animated];
PSSVSimpleBlock finishBlock = ^{
[container removeFromSuperview];
[lastController viewDidDisappear:animated];
[self delegateDidRemoveViewController:lastController];
};
if (animated) { // kPSSVStackAnimationDuration
[UIView animateWithDuration:kPSSVStackAnimationPopDuration delay:0.f options:UIViewAnimationOptionBeginFromCurrentState animations:^(void) {
lastController.containerView.alpha = 0.f;
lastController.containerView.transform = CGAffineTransformMakeScale(0.8, 0.8); // make smaller while fading out
} completion:^(BOOL finished) {
// even with duration = 0, this doesn't fire instantly but on a future runloop with NSFireDelayedPerform, thus ugly double-check
if (finished) {
finishBlock();
}
}];
}
else {
finishBlock();
}
[viewControllers_ removeLastObject];
// save current stack controller as an associated object.
objc_setAssociatedObject(lastController, kPSSVAssociatedStackViewControllerKey, nil, OBJC_ASSOCIATION_ASSIGN);
// realign view controllers
[self updateViewControllerMasksAndShadow];
[self alignStackAnimated:animated];
}
return lastController;
}
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated; {
NSMutableArray *array = [NSMutableArray array];
while ([self.viewControllers count] > 0) {
UIViewController *vc = [self popViewControllerAnimated:animated];
[array addObject:vc];
}
return array;
}
// get view controllers that are in stack _after_ current view controller
- (NSArray *)viewControllersAfterViewController:(UIViewController *)viewController {
NSParameterAssert(viewController);
NSUInteger index = [self indexOfViewController:viewController];
if (NSNotFound == index) {
return nil;
}
NSArray *array = nil;
// don't remove view controller we've been called with
if ([self.viewControllers count] > index + 1) {
array = [self.viewControllers subarrayWithRange:NSMakeRange(index + 1, [self.viewControllers count] - index - 1)];
}
return array;
}
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated; {
NSParameterAssert(viewController);
NSUInteger index = [self indexOfViewController:viewController];
if (NSNotFound == index) {
return nil;
}
PSSVLog(@"popping to index %d, from %d", index, [self.viewControllers count]);
NSArray *controllersToRemove = [self viewControllersAfterViewController:viewController];
[controllersToRemove enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self popViewControllerAnimated:animated];
}];
return controllersToRemove;
}
- (NSArray *)controllersForClass:(Class)theClass {
NSArray *controllers = [self.viewControllers filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {