/
KVNProgress.m
1455 lines (1190 loc) · 44.3 KB
/
KVNProgress.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
//
// KVNProgress.m
// KVNProgress
//
// Created by Kevin Hirsch on 24/05/14.
// Copyright (c) 2014 Kevin Hirsch. All rights reserved.
//
@import QuartzCore;
@import GLKit;
#import "KVNProgress.h"
#import "UIImage+KVNImageEffects.h"
#import "UIImage+KVNEmpty.h"
#import "UIColor+KVNContrast.h"
#import "KVNRotationViewController.h"
#define KVNBlockSelf __blockSelf
#define KVNPrepareBlockSelf() __weak typeof(self) KVNBlockSelf = self
#define KVNIpad UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
#define KVNSystemVersionGreaterOrEqual_iOS_8 ([[[UIDevice currentDevice] systemVersion] compare:@"8" options:NSNumericSearch] != NSOrderedAscending)
#define KVNRadiansToDegress(radians) ((radians) * (180.0 / M_PI))
typedef NS_ENUM(NSUInteger, KVNProgressState) {
KVNProgressStateHidden,
KVNProgressStateAppearing,
KVNProgressStateShowed,
KVNProgressStateDismissing
};
static CGFloat const KVNFadeAnimationDuration = 0.3f;
static CGFloat const KVNLayoutAnimationDuration = 0.3f;
static CGFloat const KVNTextUpdateAnimationDuration = 0.5f;
static CGFloat const KVNCheckmarkAnimationDuration = 0.5f;
static CGFloat const KVNInfiniteLoopAnimationDuration = 1.0f;
static CGFloat const KVNProgressAnimationDuration = 0.25f;
static CGFloat const KVNProgressIndeterminate = CGFLOAT_MAX;
static CGFloat const KVNCircleProgressViewToStatusLabelVerticalSpaceConstraintConstant = 20.0f;
static CGFloat const KVNContentViewFullScreenModeLeadingAndTrailingSpaceConstraintConstant = 0.0f;
static CGFloat const KVNContentViewNotFullScreenModeLeadingAndTrailingSpaceConstraintConstant = 25.0f;
static CGFloat const KVNContentViewWithStatusInset = 10.0f;
static CGFloat const KVNContentViewWithoutStatusInset = 20.0f;
static CGFloat const KVNContentViewCornerRadius = 8.0f;
static CGFloat const KVNContentViewWithoutStatusCornerRadius = 15.0f;
static CGFloat const KVNAlertViewWidth = 270.0f;
static CGFloat const KVNMotionEffectRelativeValue = 10.0f;
static KVNProgressConfiguration *configuration;
@interface KVNProgress ()
@property (nonatomic) CGFloat progress;
@property (nonatomic) KVNProgressBackgroundType backgroundType;
@property (nonatomic) NSString *status;
@property (nonatomic) KVNProgressConfiguration *configuration;
@property (nonatomic) NSDate *showActionTrigerredDate;
@property (nonatomic, getter = isFullScreen) BOOL fullScreen;
@property (nonatomic, getter = isWaitingToChangeHUD) BOOL waitingToChangeHUD;
@property (nonatomic) KVNProgressState state;
// UI
@property (nonatomic, weak) IBOutlet UIImageView *contentView;
@property (nonatomic, weak) IBOutlet UIView *circleProgressView;
@property (nonatomic, weak) IBOutlet UILabel *statusLabel;
@property (nonatomic, weak) IBOutlet UIImageView *backgroundImageView;
@property (nonatomic, strong) CAShapeLayer *checkmarkLayer;
@property (nonatomic, strong) CAShapeLayer *crossLayer;
@property (nonatomic, strong) CAShapeLayer *circleProgressLineLayer;
@property (nonatomic, strong) CAShapeLayer *circleBackgroundLineLayer;
@property (nonatomic, strong) CAShapeLayer *stopLayer;
@property (nonatomic) UIStatusBarStyle rootControllerStatusBarStyle;
// Constraints
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *circleProgressViewWidthConstraint;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *circleProgressViewHeightConstraint;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *circleProgressViewToStatusLabelVerticalSpaceConstraint;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *statusLabelHeightConstraint;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *circleProgressViewTopToSuperViewConstraint;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *statusLabelBottomToSuperViewConstraint;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *contentViewWidthConstraint;
@property (nonatomic) NSArray *constraintsToSuperview;
@property (atomic) NSOperationQueue *queue;
@property (atomic) NSBlockOperation *animateAppearanceOperation;
@property (nonatomic, strong) UIWindow *progressWindow;
@property (nonatomic, strong) UIWindow *originalKeyWindow;
@property (nonatomic, strong) UINotificationFeedbackGenerator *feedbackGenerator API_AVAILABLE(ios(10.0));
@end
@implementation KVNProgress
#pragma mark - Shared
+ (KVNProgress *)sharedView
{
static KVNProgress *sharedView = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
UINib *nib = [UINib nibWithNibName:@"KVNProgressView"
bundle:[NSBundle bundleForClass:[KVNProgress class]]];
NSArray *nibViews = [nib instantiateWithOwner:self
options:0];
sharedView = nibViews[0];
sharedView.queue = [NSOperationQueue mainQueue];
sharedView.queue.maxConcurrentOperationCount = 1;
});
return sharedView;
}
#pragma mark - Life cycle
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
if (!configuration) {
configuration = [KVNProgressConfiguration defaultConfiguration];
}
_configuration = configuration;
[self registerForNotifications];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Notifications
- (void)registerForNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidBecomeActive)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationDidChange:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
}
- (void)applicationDidBecomeActive
{
if (self.state == KVNProgressStateShowed
&& self.style == KVNProgressStyleProgress
&& self.progress == KVNProgressIndeterminate) {
// Re-starts the infinite animation
[self animateCircleWithInfiniteLoop];
}
}
- (void)orientationDidChange:(NSNotification *)notification {
if (![self.class isVisible]) {
return;
}
if ([self.superview isKindOfClass:[UIWindow class]]) {
KVNPrepareBlockSelf();
[UIView animateWithDuration:0.3f
animations:^{
[KVNBlockSelf updateUIForOrientation];
}];
} else {
[self updateUIForOrientation];
}
}
#pragma mark - Loading
+ (void)show
{
[self showWithStatus:nil];
}
+ (void)showWithStatus:(NSString *)status
{
[self showWithStatus:status
onView:nil];
}
+ (void)showWithStatus:(NSString *)status
onView:(UIView *)superview
{
[self showHUDWithProgress:KVNProgressIndeterminate
style:KVNProgressStyleProgress
status:status
superview:superview
completion:nil];
}
#pragma mark - Progress
+ (void)showProgress:(CGFloat)progress
{
[self showProgress:progress
status:nil];
}
+ (void)showProgress:(CGFloat)progress
status:(NSString*)status
{
[self showProgress:progress
status:status
onView:nil];
}
+ (void)showProgress:(CGFloat)progress
status:(NSString *)status
onView:(UIView *)superview
{
[self showHUDWithProgress:progress
style:KVNProgressStyleProgress
status:status
superview:superview
completion:nil];
}
#pragma mark - Success
+ (void)showSuccess
{
[self showSuccessWithStatus:nil];
}
+ (void)showSuccessWithCompletion:(KVNCompletionBlock)completion
{
[self showSuccessWithStatus:nil
completion:completion];
}
+ (void)showSuccessWithStatus:(NSString *)status
{
[self showSuccessWithStatus:status
onView:nil];
}
+ (void)showSuccessWithStatus:(NSString *)status
completion:(KVNCompletionBlock)completion
{
[self showSuccessWithStatus:status
onView:nil
completion:completion];
}
+ (void)showSuccessWithStatus:(NSString *)status
onView:(UIView *)superview
{
[self showSuccessWithStatus:status
onView:superview
completion:nil];
}
+ (void)showSuccessWithStatus:(NSString *)status
onView:(UIView *)superview
completion:(KVNCompletionBlock)completion
{
[self showHUDWithProgress:KVNProgressIndeterminate
style:KVNProgressStyleSuccess
status:status
superview:superview
completion:completion];
}
#pragma mark - Error
+ (void)showError
{
[self showErrorWithStatus:nil];
}
+ (void)showErrorWithCompletion:(KVNCompletionBlock)completion
{
[self showErrorWithStatus:nil
completion:completion];
}
+ (void)showErrorWithStatus:(NSString *)status
{
[self showErrorWithStatus:status
onView:nil];
}
+ (void)showErrorWithStatus:(NSString *)status
completion:(KVNCompletionBlock)completion
{
[self showErrorWithStatus:status
onView:nil
completion:completion];
}
+ (void)showErrorWithStatus:(NSString *)status
onView:(UIView *)superview
{
[self showErrorWithStatus:status
onView:superview
completion:nil];
}
+ (void)showErrorWithStatus:(NSString *)status
onView:(UIView *)superview
completion:(KVNCompletionBlock)completion
{
[self showHUDWithProgress:KVNProgressIndeterminate
style:KVNProgressStyleError
status:status
superview:superview
completion:completion];
}
#pragma mark - Show
+ (void)showHUDWithProgress:(CGFloat)progress
style:(KVNProgressStyle)style
status:(NSString *)status
superview:(UIView *)superview
completion:(KVNCompletionBlock)completion
{
[[self sharedView] showProgress:progress
status:status
style:style
backgroundType:configuration.backgroundType
fullScreen:configuration.fullScreen
view:superview
completion:completion];
}
- (void)showProgress:(CGFloat)progress
status:(NSString *)status
style:(KVNProgressStyle)style
backgroundType:(KVNProgressBackgroundType)backgroundType
fullScreen:(BOOL)fullScreen
view:(UIView *)superview
completion:(KVNCompletionBlock)completion
{
KVNPrepareBlockSelf();
// We check if a previous HUD is displaying
// If so, we wait its minimum display time before switching to the new one
// But, if we are changing from an indeterminate progress HUD to a determinate one,
// we do not apply this rule
if (![self isWaitingToChangeHUD] && self.style != KVNProgressStyleHidden
&& !(self.style == KVNProgressStyleProgress && self.progress == KVNProgressIndeterminate && progress != KVNProgressIndeterminate)
&& !(self.style == KVNProgressStyleProgress && self.progress != KVNProgressIndeterminate)) {
self.waitingToChangeHUD = YES;
self.state = KVNProgressStateShowed;
NSTimeInterval timeIntervalSinceShow = [self.showActionTrigerredDate timeIntervalSinceNow];
NSTimeInterval delay = 0;
if (timeIntervalSinceShow < self.configuration.minimumDisplayTime) {
// The hud hasn't showed enough time
timeIntervalSinceShow = (timeIntervalSinceShow < 0) ? 0 : timeIntervalSinceShow;
delay = self.configuration.minimumDisplayTime - timeIntervalSinceShow;
}
if (delay > 0) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (KVNBlockSelf.state == KVNProgressStateDismissing || ![KVNBlockSelf.class isVisible]) {
// While waiting for displaying previous HUD enough time before showing the new one,
// the dismiss method on this new HUD has already been called
// So logically, we do not display the new HUD that is already dismissed (before even being displayed)
return;
}
[KVNBlockSelf showProgress:progress
status:status
style:style
backgroundType:backgroundType
fullScreen:fullScreen
view:superview
completion:completion];
});
return;
}
}
// We're going to create a new HUD
self.waitingToChangeHUD = NO;
self.progress = progress;
self.status = [status copy];
self.style = style;
self.backgroundType = backgroundType;
self.fullScreen = fullScreen;
// If HUD is already added to the view we just update the UI
if ([self.class isVisible]) {
self.state = KVNProgressStateShowed;
[UIView animateWithDuration:KVNLayoutAnimationDuration
animations:^{
[KVNBlockSelf setupUI:NO];
}];
KVNBlockSelf.showActionTrigerredDate = [NSDate date];
[KVNBlockSelf animateUI];
} else {
self.state = KVNProgressStateAppearing;
if (superview) {
[self addToView:superview];
} else {
[self addToWindow];
}
[self setupUI:YES];
self.animateAppearanceOperation = [NSBlockOperation blockOperationWithBlock:^{
[KVNBlockSelf animateUI];
[KVNBlockSelf animateAppearance];
}];
// FIXME: find a way to wait for the views to be added to the window before launching the animations
// (Fix to make the animations work fine)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (![KVNBlockSelf.queue.operations containsObject:KVNBlockSelf.animateAppearanceOperation] &&
![KVNBlockSelf.animateAppearanceOperation isFinished])
{
[KVNBlockSelf.queue addOperation:KVNBlockSelf.animateAppearanceOperation];
}
});
}
// If it's an auto-dismissable HUD
if (self.style != KVNProgressStyleProgress) {
NSTimeInterval delay;
switch (self.style) {
case KVNProgressStyleProgress:
// should never happen
return;
case KVNProgressStyleSuccess:
delay = self.configuration.minimumSuccessDisplayTime;
break;
case KVNProgressStyleError:
delay = self.configuration.minimumErrorDisplayTime;
break;
case KVNProgressStyleHidden:
// should never happen
return;
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[KVNBlockSelf.class dismissWithCompletion:completion];
});
}
if (@available(iOS 10.0, *)) {
[self sendUIFeedbackIfNeededFor:self.style];
}
}
- (UIView *)accessibilityView
{
if ([self.superview isKindOfClass:UIWindow.class]) {
return self;
} else if (self.superview) {
return self.superview;
} else {
return nil;
}
}
- (void)sendUIFeedbackIfNeededFor:(KVNProgressStyle)style API_AVAILABLE(ios(10.0))
{
if (!configuration.isUIFeedbackEnabled) {
return;
}
if (!self.feedbackGenerator) {
self.feedbackGenerator = [[UINotificationFeedbackGenerator alloc] init];
}
switch (style) {
case KVNProgressStyleProgress:
[self.feedbackGenerator prepare];
break;
case KVNProgressStyleSuccess:
[self.feedbackGenerator notificationOccurred:UINotificationFeedbackTypeSuccess];
break;
case KVNProgressStyleError:
[self.feedbackGenerator notificationOccurred:UINotificationFeedbackTypeError];
break;
case KVNProgressStyleHidden:
break;
}
}
#pragma mark - Dimiss
+ (void)dismiss
{
[self dismissWithCompletion:nil];
}
+ (void)dismissWithCompletion:(KVNCompletionBlock)completion
{
if ([self sharedView].state == KVNProgressStateHidden) {
return;
} else if ([self sharedView].state == KVNProgressStateAppearing) {
[self sharedView].state = KVNProgressStateDismissing;
[[self sharedView].animateAppearanceOperation cancel];
[self endDismissWithCompletion:completion];
return;
}
[self sharedView].state = KVNProgressStateDismissing;
// FIXME: find a way to wait for the views to be added to the window before launching the animations
// (Fix to make the dismiss work fine)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// If the view has changed or will change, the state property is set back to showed so we don't dismiss
// the (scheduled) new one
if ([self sharedView].state == KVNProgressStateDismissing) {
[self dismissAnimatedWithCompletion:completion];
}
});
}
+ (void)dismissAnimatedWithCompletion:(KVNCompletionBlock)completion
{
KVNProgress *progressView = [self sharedView];
NSTimeInterval timeIntervalSinceShow = fabs([progressView.showActionTrigerredDate timeIntervalSinceNow]);
NSTimeInterval delay = 0;
if (timeIntervalSinceShow < progressView.configuration.minimumDisplayTime) {
// The hud hasn't showed enough time
delay = progressView.configuration.minimumDisplayTime - timeIntervalSinceShow;
}
[UIView animateWithDuration:KVNFadeAnimationDuration
delay:delay
options:(UIViewAnimationOptionCurveEaseIn
| UIViewAnimationOptionAllowUserInteraction
| UIViewAnimationOptionBeginFromCurrentState)
animations:^{
if ([self sharedView].state == KVNProgressStateDismissing) {
progressView.alpha = 0.0f;
}
} completion:^(BOOL finished) {
if(progressView.alpha == 0 || progressView.contentView.alpha == 0) {
[self endDismissWithCompletion:completion];
}
}];
}
+ (void)endDismissWithCompletion:(KVNCompletionBlock)completion
{
KVNProgress *progressView = [self sharedView];
if (progressView.state == KVNProgressStateDismissing) {
[self sharedView].state = KVNProgressStateHidden;
progressView.accessibilityView.isAccessibilityElement = NO;
progressView.accessibilityView.accessibilityLabel = nil;
[progressView cancelCircleAnimation];
[progressView removeFromSuperview];
progressView.style = KVNProgressStyleHidden;
if (!progressView.progressWindow.hidden) {
progressView.progressWindow.hidden = YES;
[progressView.originalKeyWindow makeKeyAndVisible];
}
[UIApplication sharedApplication].statusBarStyle = [self sharedView].rootControllerStatusBarStyle;
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);
}
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
}
#pragma mark - UI
- (void)setupUI:(BOOL)needSetupStatusBar
{
if (needSetupStatusBar) {
[self setupStatusBar];
}
[self setupGestures];
[self setupConstraints];
[self setupCircleProgressView];
[self setupStatus:self.status];
[self setupBackground];
self.accessibilityView.isAccessibilityElement = YES;
self.accessibilityView.accessibilityLabel = self.accessibilityStatus;
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self.accessibilityView);
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, self.accessibilityView);
[self setNeedsFocusUpdate];
[self updateFocusIfNeeded];
}
- (void)setupStatusBar
{
self.rootControllerStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
if (![self isFullScreen]) {
return;
}
UIColor *backgroundColor;
switch (self.backgroundType) {
case KVNProgressBackgroundTypeBlurred: {
backgroundColor = self.configuration.backgroundTintColor;
break;
}
case KVNProgressBackgroundTypeSolid: {
backgroundColor = self.configuration.backgroundFillColor;
break;
}
}
[UIApplication sharedApplication].statusBarStyle = [backgroundColor statusBarStyleConstrastStyle];
}
- (void)setupGestures
{
for (UIGestureRecognizer *gestureRecognizer in self.gestureRecognizers) {
[self removeGestureRecognizer:gestureRecognizer];
}
if (self.configuration.tapBlock) {
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(performTapBlock)];
[self addGestureRecognizer:tapGestureRecognizer];
}
}
- (void)setupConstraints
{
CGRect bounds = [self correctedBounds];
CGFloat statusInset = (self.status.length > 0) ? KVNContentViewWithStatusInset : KVNContentViewWithoutStatusInset;
CGFloat contentWidth;
if (!KVNSystemVersionGreaterOrEqual_iOS_8 && [self.superview isKindOfClass:UIWindow.class]) {
self.transform = CGAffineTransformMakeRotation([self rotationForStatusBarOrientation]);
} else {
self.transform = CGAffineTransformIdentity;
}
if ([self isFullScreen]) {
contentWidth = CGRectGetWidth(bounds) - (2 * KVNContentViewFullScreenModeLeadingAndTrailingSpaceConstraintConstant);
} else {
if (KVNIpad) {
contentWidth = KVNAlertViewWidth;
} else {
contentWidth = CGRectGetWidth(bounds) - (2 * KVNContentViewNotFullScreenModeLeadingAndTrailingSpaceConstraintConstant);
if (contentWidth > KVNAlertViewWidth) {
contentWidth = KVNAlertViewWidth;
}
}
}
self.circleProgressViewTopToSuperViewConstraint.constant = statusInset;
self.statusLabelBottomToSuperViewConstraint.constant = statusInset;
self.contentViewWidthConstraint.constant = contentWidth;
[self layoutIfNeeded];
}
- (void)setupCircleProgressView
{
// Constraints
self.circleProgressViewWidthConstraint.constant = self.configuration.circleSize;
self.circleProgressViewHeightConstraint.constant = self.configuration.circleSize;
[self layoutIfNeeded];
// Circle shape
self.circleProgressView.layer.cornerRadius = (self.configuration.circleSize / 2.0f);
self.circleProgressView.layer.masksToBounds = YES;
self.circleProgressView.backgroundColor = [UIColor clearColor];
// Remove all previous added layers
[self removeAllSubLayersOfLayer:self.circleProgressView.layer];
}
- (void)setupInfiniteCircle
{
CGFloat radius = (self.configuration.circleSize / 2.0f);
CGPoint center = CGPointMake(radius, radius);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center
radius:(radius - self.configuration.lineWidth)
startAngle:GLKMathDegreesToRadians(-45.0f)
endAngle:GLKMathDegreesToRadians(275.0f)
clockwise:YES];
self.circleProgressLineLayer = [CAShapeLayer layer];
self.circleProgressLineLayer.path = circlePath.CGPath;
self.circleProgressLineLayer.strokeColor = self.configuration.circleStrokeForegroundColor.CGColor;
self.circleProgressLineLayer.fillColor = self.configuration.circleFillBackgroundColor.CGColor;
self.circleProgressLineLayer.lineWidth = self.configuration.lineWidth;
[self.circleProgressView.layer addSublayer:self.circleProgressLineLayer];
[self.circleProgressLineLayer removeAllAnimations];
[self.circleProgressView.layer removeAllAnimations];
[self animateCircleWithInfiniteLoop];
}
- (void)setupProgressCircle
{
CGFloat radius = (self.configuration.circleSize / 2.0f);
CGPoint center = CGPointMake(radius, radius);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center
radius:(radius - self.configuration.lineWidth)
startAngle:GLKMathDegreesToRadians(-90.0f)
endAngle:GLKMathDegreesToRadians(275.0f)
clockwise:YES];
[self cancelCircleAnimation];
self.circleProgressLineLayer = [CAShapeLayer layer];
self.circleProgressLineLayer.path = circlePath.CGPath;
self.circleProgressLineLayer.strokeColor = self.configuration.circleStrokeForegroundColor.CGColor;
self.circleProgressLineLayer.fillColor = [UIColor clearColor].CGColor;
self.circleProgressLineLayer.lineWidth = self.configuration.lineWidth;
self.circleBackgroundLineLayer = [CAShapeLayer layer];
self.circleBackgroundLineLayer.path = circlePath.CGPath;
self.circleBackgroundLineLayer.strokeColor = self.configuration.circleStrokeBackgroundColor.CGColor;
self.circleBackgroundLineLayer.fillColor = self.configuration.circleFillBackgroundColor.CGColor;
self.circleBackgroundLineLayer.lineWidth = self.configuration.lineWidth;
[self.circleProgressView.layer addSublayer:self.circleBackgroundLineLayer];
[self.circleProgressView.layer addSublayer:self.circleProgressLineLayer];
[self.circleProgressLineLayer removeAllAnimations];
[self.circleProgressView.layer removeAllAnimations];
[self updateProgress:self.progress
animated:NO];
}
- (void)setupSuccessUI
{
[self setupFullRoundCircleWithColor:self.configuration.successColor];
self.stopLayer.opacity = 0.0f;
UIBezierPath* checkmarkPath = [UIBezierPath bezierPath];
[checkmarkPath moveToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.28f, CGRectGetHeight(self.circleProgressView.bounds) * 0.53f)];
[checkmarkPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.42f, CGRectGetHeight(self.circleProgressView.bounds) * 0.66f)];
[checkmarkPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.72f, CGRectGetHeight(self.circleProgressView.bounds) * 0.36f)];
checkmarkPath.lineCapStyle = kCGLineCapSquare;
self.checkmarkLayer = [CAShapeLayer layer];
self.checkmarkLayer.path = checkmarkPath.CGPath;
self.checkmarkLayer.fillColor = nil;
self.checkmarkLayer.strokeColor = self.configuration.successColor.CGColor;
self.checkmarkLayer.lineWidth = self.configuration.lineWidth;
[self.circleProgressView.layer addSublayer:self.circleProgressLineLayer];
[self.circleProgressView.layer addSublayer:self.checkmarkLayer];
[self.circleProgressLineLayer removeAllAnimations];
[self.circleProgressView.layer removeAllAnimations];
[self.checkmarkLayer removeAllAnimations];
[self animateSuccess];
}
- (void)setupErrorUI
{
[self setupFullRoundCircleWithColor:self.configuration.errorColor];
self.stopLayer.opacity = 0.0f;
UIBezierPath* crossPath = [UIBezierPath bezierPath];
[crossPath moveToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.72f, CGRectGetHeight(self.circleProgressView.bounds) * 0.27f)];
[crossPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.27f, CGRectGetHeight(self.circleProgressView.bounds) * 0.72f)];
[crossPath moveToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.27f, CGRectGetHeight(self.circleProgressView.bounds) * 0.27f)];
[crossPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * 0.72f, CGRectGetHeight(self.circleProgressView.bounds) * 0.72f)];
crossPath.lineCapStyle = kCGLineCapSquare;
self.crossLayer = [CAShapeLayer layer];
self.crossLayer.path = crossPath.CGPath;
self.crossLayer.fillColor = nil;
self.crossLayer.strokeColor = self.configuration.errorColor.CGColor;
self.crossLayer.lineWidth = self.configuration.lineWidth;
[self.circleProgressView.layer addSublayer:self.circleProgressLineLayer];
[self.circleProgressView.layer addSublayer:self.crossLayer];
[self.circleProgressLineLayer removeAllAnimations];
[self.circleProgressView.layer removeAllAnimations];
[self.crossLayer removeAllAnimations];
[self animateError];
}
- (void)setupStopUI
{
if (![self.configuration doesShowStop]
|| !self.configuration.tapBlock
|| [configuration doesAllowUserInteraction])
{
return;
}
self.stopLayer.opacity = 1.0f;
CGFloat squareBegin = 0.5f - (self.configuration.stopRelativeHeight / 2.0f);
CGFloat squareEnd = squareBegin + self.configuration.stopRelativeHeight;
UIBezierPath* stopPath = [UIBezierPath bezierPath];
[stopPath moveToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * squareEnd, CGRectGetHeight(self.circleProgressView.bounds) * squareEnd)];
[stopPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * squareBegin, CGRectGetHeight(self.circleProgressView.bounds) * squareEnd)];
[stopPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * squareBegin, CGRectGetHeight(self.circleProgressView.bounds) * squareBegin)];
[stopPath addLineToPoint:CGPointMake(CGRectGetWidth(self.circleProgressView.bounds) * squareEnd, CGRectGetHeight(self.circleProgressView.bounds) * squareBegin)];
[stopPath closePath];
stopPath.lineCapStyle = kCGLineCapSquare;
self.stopLayer = [CAShapeLayer layer];
self.stopLayer.path = stopPath.CGPath;
self.stopLayer.fillColor = self.configuration.stopColor.CGColor;
[self.circleProgressView.layer addSublayer:self.circleProgressLineLayer];
[self.circleProgressView.layer addSublayer:self.stopLayer];
[self.circleProgressLineLayer removeAllAnimations];
[self.circleProgressView.layer removeAllAnimations];
}
- (void)setupFullRoundCircleWithColor:(UIColor *)color
{
CGFloat radius = (self.configuration.circleSize / 2.0f);
CGPoint center = CGPointMake(radius, radius);
// Circle
UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center
radius:(radius - self.configuration.lineWidth)
startAngle:GLKMathDegreesToRadians(-90.0f)
endAngle:GLKMathDegreesToRadians(275.0f)
clockwise:YES];
self.circleProgressLineLayer = [CAShapeLayer layer];
self.circleProgressLineLayer.path = circlePath.CGPath;
self.circleProgressLineLayer.strokeColor = color.CGColor;
self.circleProgressLineLayer.fillColor = self.configuration.circleFillBackgroundColor.CGColor;
self.circleProgressLineLayer.lineWidth = self.configuration.lineWidth;
}
- (void)setupStatus:(NSString *)status
{
self.status = status;
BOOL showStatus = (self.status.length > 0);
CATransition *animation = [CATransition animation];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = kCATransitionFade;
animation.duration = KVNTextUpdateAnimationDuration;
[self.statusLabel.layer addAnimation:animation forKey:@"kCATransitionFade"];
self.statusLabel.text = self.status;
self.statusLabel.textColor = self.configuration.statusColor;
self.statusLabel.font = self.configuration.statusFont;
self.statusLabel.hidden = !showStatus;
[self updateStatusConstraints];
}
- (void)setupBackground
{
if ([self.class isVisible]) {
[self updateBackgroundConstraints];
[self layoutIfNeeded];
return; // No reload of background when view is showing
}
[self updateBackground];
KVNPrepareBlockSelf();
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[KVNBlockSelf setupMotionEffect];
});
}
- (void)setupMotionEffect
{
UIInterpolatingMotionEffect *xAxis = [self motionEffectWithType:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis
keyPath:@"center.x"];
UIInterpolatingMotionEffect *yAxis = [self motionEffectWithType:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis
keyPath:@"center.y"];
UIMotionEffectGroup *group = [[UIMotionEffectGroup alloc] init];
group.motionEffects = @[xAxis, yAxis];
[self.contentView addMotionEffect:group];
}
- (void)addToWindow
{
self.originalKeyWindow = [UIApplication sharedApplication].keyWindow;
if (!self.progressWindow) {
self.progressWindow = [[UIWindow alloc] initWithFrame:self.originalKeyWindow.frame];
// That code makes the custom UIWindow handle the orientation changes.
// http://stackoverflow.com/a/27091111/2571566
self.progressWindow.rootViewController = [[KVNRotationViewController alloc] init];
}
self.progressWindow.frame = self.originalKeyWindow.frame;
// Since iOS 9.0 set the windowsLevel to UIWindowLevelStatusBar is not working anymore.
// This trick, place the progressWindow on the top.
UIWindow *lastWindow = [[[UIApplication sharedApplication] windows] lastObject];
self.progressWindow.windowLevel = lastWindow.windowLevel + 1;
[self.progressWindow makeKeyAndVisible];
[self addToView:self.progressWindow];
}
- (void)addToView:(UIView *)superview
{
if (self.superview == superview) {
return;
}
if (self.superview) {
[self.superview removeConstraints:self.constraintsToSuperview];
[self removeFromSuperview];
}
[superview addSubview:self];
[superview bringSubviewToFront:self];
if (![superview isKindOfClass:[UITableView class]]) {
// Autolayout messes when superview is a UITableView
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[self]|"
options:0
metrics:nil
views:@{@"self" : self}];
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[self]|"
options:0
metrics:nil
views:@{@"self" : self}];
self.constraintsToSuperview = [verticalConstraints arrayByAddingObjectsFromArray:horizontalConstraints];
self.translatesAutoresizingMaskIntoConstraints = NO;
[superview addConstraints:verticalConstraints];
[superview addConstraints:horizontalConstraints];
[self layoutIfNeeded];
}
self.alpha = 0.0f;
// Fix for non autolayout project
self.frame = superview.bounds;
}
#pragma mark - Update
- (void)updateUIForOrientation
{
[self setupConstraints];
[self updateStatusConstraints];
[self updateBackgroundConstraints];
}
- (void)updateBackground
{
UIImage *backgroundImage = nil;
UIColor *backgroundColor = nil;
switch (self.backgroundType) {
case KVNProgressBackgroundTypeSolid:
backgroundImage = [UIImage emptyImage];
backgroundColor = self.configuration.backgroundFillColor;
break;
case KVNProgressBackgroundTypeBlurred:
backgroundImage = [self blurredScreenShot];