/
SVProgressHUD.m
1446 lines (1176 loc) · 54.7 KB
/
SVProgressHUD.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
//
// SVProgressHUD.h
// SVProgressHUD, https://github.com/SVProgressHUD/SVProgressHUD
//
// Copyright (c) 2011-2016 Sam Vermette and contributors. All rights reserved.
//
#if !__has_feature(objc_arc)
#error SVProgressHUD is ARC only. Either turn on ARC for the project or use -fobjc-arc flag
#endif
#import "SVProgressHUD.h"
#import "SVIndefiniteAnimatedView.h"
#import "SVProgressAnimatedView.h"
#import "SVRadialGradientLayer.h"
NSString * const SVProgressHUDDidReceiveTouchEventNotification = @"SVProgressHUDDidReceiveTouchEventNotification";
NSString * const SVProgressHUDDidTouchDownInsideNotification = @"SVProgressHUDDidTouchDownInsideNotification";
NSString * const SVProgressHUDWillDisappearNotification = @"SVProgressHUDWillDisappearNotification";
NSString * const SVProgressHUDDidDisappearNotification = @"SVProgressHUDDidDisappearNotification";
NSString * const SVProgressHUDWillAppearNotification = @"SVProgressHUDWillAppearNotification";
NSString * const SVProgressHUDDidAppearNotification = @"SVProgressHUDDidAppearNotification";
NSString * const SVProgressHUDStatusUserInfoKey = @"SVProgressHUDStatusUserInfoKey";
static const CGFloat SVProgressHUDParallaxDepthPoints = 10.0f;
static const CGFloat SVProgressHUDUndefinedProgress = -1;
static const CGFloat SVProgressHUDDefaultAnimationDuration = 0.15f;
static const CGFloat SVProgressHUDVerticalSpacing = 12.0f;
static const CGFloat SVProgressHUDHorizontalSpacing = 12.0f;
static const CGFloat SVProgressHUDLabelSpacing = 8.0f;
@interface SVProgressHUD ()
@property (nonatomic, strong) NSTimer *fadeOutTimer;
@property (nonatomic, strong) UIControl *controlView;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) SVRadialGradientLayer *backgroundRadialGradientLayer;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) UIVisualEffectView *hudView;
@property (nonatomic, strong) UIVisualEffectView *hudVibrancyView;
#else
@property (nonatomic, strong) UIView *hudView;
#endif
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *indefiniteAnimatedView;
@property (nonatomic, strong) SVProgressAnimatedView *ringView;
@property (nonatomic, strong) SVProgressAnimatedView *backgroundRingView;
@property (nonatomic, readwrite) CGFloat progress;
@property (nonatomic, readwrite) NSUInteger activityCount;
@property (nonatomic, readonly) CGFloat visibleKeyboardHeight;
@property (nonatomic, readonly) UIWindow *frontWindow;
- (void)updateHUDFrame;
#if TARGET_OS_IOS
- (void)updateMotionEffectForOrientation:(UIInterfaceOrientation)orientation;
#endif
- (void)updateMotionEffectForXMotionEffectType:(UIInterpolatingMotionEffectType)xMotionEffectType yMotionEffectType:(UIInterpolatingMotionEffectType)yMotionEffectType;
- (void)updateViewHierarchy;
- (void)setStatus:(NSString*)status;
- (void)setFadeOutTimer:(NSTimer*)timer;
- (void)registerNotifications;
- (NSDictionary*)notificationUserInfo;
- (void)positionHUD:(NSNotification*)notification;
- (void)moveToPoint:(CGPoint)newCenter rotateAngle:(CGFloat)angle;
- (void)controlViewDidReceiveTouchEvent:(id)sender forEvent:(UIEvent*)event;
- (void)showProgress:(float)progress status:(NSString*)status;
- (void)showImage:(UIImage*)image status:(NSString*)status duration:(NSTimeInterval)duration;
- (void)showStatus:(NSString*)status;
- (void)dismiss;
- (void)dismissWithDelay:(NSTimeInterval)delay completion:(SVProgressHUDDismissCompletion)completion;
- (void)cancelRingLayerAnimation;
- (void)cancelIndefiniteAnimatedViewAnimation;
- (UIColor*)foregroundColorForStyle;
- (UIColor*)backgroundColorForStyle;
@end
@implementation SVProgressHUD {
BOOL _isInitializing;
}
+ (SVProgressHUD*)sharedView {
static dispatch_once_t once;
static SVProgressHUD *sharedView;
#if !defined(SV_APP_EXTENSIONS)
dispatch_once(&once, ^{ sharedView = [[self alloc] initWithFrame:[[[UIApplication sharedApplication] delegate] window].bounds]; });
#else
dispatch_once(&once, ^{ sharedView = [[self alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; });
#endif
return sharedView;
}
#pragma mark - Setters
+ (void)setStatus:(NSString*)status {
[[self sharedView] setStatus:status];
}
+ (void)setDefaultStyle:(SVProgressHUDStyle)style {
[self sharedView].defaultStyle = style;
}
+ (void)setDefaultMaskType:(SVProgressHUDMaskType)maskType {
[self sharedView].defaultMaskType = maskType;
}
+ (void)setDefaultAnimationType:(SVProgressHUDAnimationType)type {
[self sharedView].defaultAnimationType = type;
}
+ (void)setContainerView:(UIView *)containerView {
[self sharedView].containerView = containerView;
}
+ (void)setMinimumSize:(CGSize)minimumSize {
[self sharedView].minimumSize = minimumSize;
}
+ (void)setRingThickness:(CGFloat)ringThickness {
[self sharedView].ringThickness = ringThickness;
}
+ (void)setRingRadius:(CGFloat)radius {
[self sharedView].ringRadius = radius;
}
+ (void)setRingNoTextRadius:(CGFloat)radius {
[self sharedView].ringNoTextRadius = radius;
}
+ (void)setCornerRadius:(CGFloat)cornerRadius {
[self sharedView].cornerRadius = cornerRadius;
}
+ (void)setFont:(UIFont*)font {
[self sharedView].font = font;
}
+ (void)setForegroundColor:(UIColor*)color {
[self sharedView].foregroundColor = color;
[self sharedView].defaultStyle = SVProgressHUDStyleCustom;
}
+ (void)setBackgroundColor:(UIColor*)color {
[self sharedView].backgroundColor = color;
[self sharedView].defaultStyle = SVProgressHUDStyleCustom;
}
+ (void)setBackgroundLayerColor:(UIColor*)color {
[self sharedView].backgroundLayerColor = color;
}
+ (void)setInfoImage:(UIImage*)image {
[self sharedView].infoImage = image;
}
+ (void)setSuccessImage:(UIImage*)image {
[self sharedView].successImage = image;
}
+ (void)setErrorImage:(UIImage*)image {
[self sharedView].errorImage = image;
}
+ (void)setViewForExtension:(UIView*)view {
[self sharedView].viewForExtension = view;
}
+ (void)setMinimumDismissTimeInterval:(NSTimeInterval)interval {
[self sharedView].minimumDismissTimeInterval = interval;
}
+ (void)setMaximumDismissTimeInterval:(NSTimeInterval)interval {
[self sharedView].maximumDismissTimeInterval = interval;
}
+ (void)setFadeInAnimationDuration:(NSTimeInterval)duration {
[self sharedView].fadeInAnimationDuration = duration;
}
+ (void)setFadeOutAnimationDuration:(NSTimeInterval)duration {
[self sharedView].fadeOutAnimationDuration = duration;
}
+ (void)setMaxSupportedWindowLevel:(UIWindowLevel)windowLevel {
[self sharedView].maxSupportedWindowLevel = windowLevel;
}
#pragma mark - Show Methods
+ (void)show {
[self showWithStatus:nil];
}
+ (void)showWithMaskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self show];
[self setDefaultMaskType:existingMaskType];
}
+ (void)showWithStatus:(NSString*)status {
[self showProgress:SVProgressHUDUndefinedProgress status:status];
}
+ (void)showWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showWithStatus:status];
[self setDefaultMaskType:existingMaskType];
}
+ (void)showProgress:(float)progress {
[self showProgress:progress status:nil];
}
+ (void)showProgress:(float)progress maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showProgress:progress];
[self setDefaultMaskType:existingMaskType];
}
+ (void)showProgress:(float)progress status:(NSString*)status {
[[self sharedView] showProgress:progress status:status];
}
+ (void)showProgress:(float)progress status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showProgress:progress status:status];
[self setDefaultMaskType:existingMaskType];
}
#pragma mark - Show, then automatically dismiss methods
+ (void)showInfoWithStatus:(NSString*)status {
[self showImage:[self sharedView].infoImage status:status];
}
+ (void)showInfoWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showInfoWithStatus:status];
[self setDefaultMaskType:existingMaskType];
}
+ (void)showSuccessWithStatus:(NSString*)status {
[self showImage:[self sharedView].successImage status:status];
}
+ (void)showSuccessWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showSuccessWithStatus:status];
[self setDefaultMaskType:existingMaskType];
}
+ (void)showErrorWithStatus:(NSString*)status {
[self showImage:[self sharedView].errorImage status:status];
}
+ (void)showErrorWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showErrorWithStatus:status];
[self setDefaultMaskType:existingMaskType];
}
+ (void)showImage:(UIImage*)image status:(NSString*)status {
NSTimeInterval displayInterval = [self displayDurationForString:status];
[[self sharedView] showImage:image status:status duration:displayInterval];
}
+ (void)showImage:(UIImage*)image status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
SVProgressHUDMaskType existingMaskType = [self sharedView].defaultMaskType;
[self setDefaultMaskType:maskType];
[self showImage:image status:status];
[self setDefaultMaskType:existingMaskType];
}
#pragma mark - Dismiss Methods
+ (void)popActivity {
if([self sharedView].activityCount > 0) {
[self sharedView].activityCount--;
}
if([self sharedView].activityCount == 0) {
[[self sharedView] dismiss];
}
}
+ (void)dismiss {
[self dismissWithDelay:0.0 completion:nil];
}
+ (void)dismissWithCompletion:(SVProgressHUDDismissCompletion)completion {
[self dismissWithDelay:0.0 completion:completion];
}
+ (void)dismissWithDelay:(NSTimeInterval)delay {
[self dismissWithDelay:delay completion:nil];
}
+ (void)dismissWithDelay:(NSTimeInterval)delay completion:(SVProgressHUDDismissCompletion)completion {
[[self sharedView] dismissWithDelay:delay completion:completion];
}
#pragma mark - Offset
+ (void)setOffsetFromCenter:(UIOffset)offset {
[self sharedView].offsetFromCenter = offset;
}
+ (void)resetOffsetFromCenter {
[self setOffsetFromCenter:UIOffsetZero];
}
#pragma mark - Instance Methods
- (instancetype)initWithFrame:(CGRect)frame {
if((self = [super initWithFrame:frame])) {
_isInitializing = YES;
self.userInteractionEnabled = NO;
self.activityCount = 0;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
self.hudView.contentView.alpha = 0.0f;
#else
self.hudView.alpha = 0.0f;
#endif
self.backgroundView.alpha = 0.0f;
_backgroundColor = [UIColor clearColor];
_foregroundColor = [UIColor blackColor];
_backgroundLayerColor = [UIColor colorWithWhite:0 alpha:0.4];
// Set default values
_defaultMaskType = SVProgressHUDMaskTypeNone;
_defaultStyle = SVProgressHUDStyleLight;
_defaultAnimationType = SVProgressHUDAnimationTypeFlat;
_minimumSize = CGSizeZero;
_font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
NSBundle *bundle = [NSBundle bundleForClass:[SVProgressHUD class]];
NSURL *url = [bundle URLForResource:@"SVProgressHUD" withExtension:@"bundle"];
NSBundle *imageBundle = [NSBundle bundleWithURL:url];
UIImage* infoImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"info" ofType:@"png"]];
UIImage* successImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"success" ofType:@"png"]];
UIImage* errorImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"error" ofType:@"png"]];
_infoImage = [infoImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
_successImage = [successImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
_errorImage = [errorImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
_ringThickness = 2.0f;
_ringRadius = 18.0f;
_ringNoTextRadius = 24.0f;
_cornerRadius = 14.0f;
_minimumDismissTimeInterval = 5.0;
_maximumDismissTimeInterval = CGFLOAT_MAX;
_fadeInAnimationDuration = SVProgressHUDDefaultAnimationDuration;
_fadeOutAnimationDuration = SVProgressHUDDefaultAnimationDuration;
_maxSupportedWindowLevel = UIWindowLevelNormal;
// Accessibility support
self.accessibilityIdentifier = @"SVProgressHUD";
self.accessibilityLabel = @"SVProgressHUD";
self.isAccessibilityElement = YES;
_isInitializing = NO;
}
return self;
}
- (void)updateHUDFrame {
// Check if an image or progress ring is displayed
BOOL imageUsed = (self.imageView.image) && !(self.imageView.hidden);
BOOL progressUsed = self.imageView.hidden;
// Calculate size of string
CGRect labelRect = CGRectZero;
CGFloat labelHeight = 0.0f;
CGFloat labelWidth = 0.0f;
if(self.statusLabel.text) {
labelRect = [self.statusLabel.text boundingRectWithSize:CGSizeZero
options:(NSStringDrawingOptions)(NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin)
attributes:@{NSFontAttributeName: self.statusLabel.font}
context:NULL];
labelHeight = ceilf(CGRectGetHeight(labelRect));
labelWidth = ceilf(CGRectGetWidth(labelRect));
}
// Calculate hud size based on content
// For the beginning use default values, these
// might get update if string is too large etc.
CGFloat hudWidth;
CGFloat hudHeight;
CGFloat contentWidth = 0.0f;
CGFloat contentHeight = 0.0f;
if(imageUsed || progressUsed) {
contentWidth = CGRectGetWidth(imageUsed ? self.imageView.frame : self.indefiniteAnimatedView.frame);
contentHeight = CGRectGetHeight(imageUsed ? self.imageView.frame : self.indefiniteAnimatedView.frame);
}
// |-spacing-content-spacing-|
hudWidth = SVProgressHUDHorizontalSpacing + MAX(labelWidth, contentWidth) + SVProgressHUDHorizontalSpacing;
// |-spacing-content-(labelSpacing-label-)spacing-|
hudHeight = SVProgressHUDVerticalSpacing + labelHeight + contentHeight + SVProgressHUDVerticalSpacing;
if(self.statusLabel.text && (imageUsed || progressUsed)){
// Add spacing if both content and label are used
hudHeight += SVProgressHUDLabelSpacing;
}
// Update values on subviews
self.hudView.bounds = CGRectMake(0.0f, 0.0f, MAX(self.minimumSize.width, hudWidth), MAX(self.minimumSize.height, hudHeight));
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
self.hudVibrancyView.bounds = self.hudView.bounds;
#endif
// Animate value update
[CATransaction begin];
[CATransaction setDisableActions:YES];
// Spinner and image view
CGFloat centerY;
if(self.statusLabel.text) {
CGFloat yOffset = MAX(SVProgressHUDVerticalSpacing, (self.minimumSize.height - contentHeight - SVProgressHUDLabelSpacing - labelHeight) / 2.0f);
centerY = yOffset + contentHeight / 2.0f;
} else {
centerY = CGRectGetMidY(self.hudView.bounds);
}
self.indefiniteAnimatedView.center = CGPointMake(CGRectGetMidX(self.hudView.bounds), centerY);
if(self.progress != SVProgressHUDUndefinedProgress) {
self.backgroundRingView.center = self.ringView.center = CGPointMake(CGRectGetMidX(self.hudView.bounds), centerY);
}
self.imageView.center = CGPointMake(CGRectGetMidX(self.hudView.bounds), centerY);
// Label
if(imageUsed || progressUsed) {
centerY = CGRectGetMaxY(imageUsed ? self.imageView.frame : self.indefiniteAnimatedView.frame) + SVProgressHUDLabelSpacing + labelHeight / 2.0f;
} else {
centerY = CGRectGetMidY(self.hudView.bounds);
}
self.statusLabel.frame = labelRect;
self.statusLabel.center = CGPointMake(CGRectGetMidX(self.hudView.bounds), centerY);
self.statusLabel.hidden = !self.statusLabel.text;
[CATransaction commit];
}
#if TARGET_OS_IOS
- (void)updateMotionEffectForOrientation:(UIInterfaceOrientation)orientation {
UIInterpolatingMotionEffectType xMotionEffectType = UIInterfaceOrientationIsPortrait(orientation) ? UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis : UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis;
UIInterpolatingMotionEffectType yMotionEffectType = UIInterfaceOrientationIsPortrait(orientation) ? UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis : UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis;
[self updateMotionEffectForXMotionEffectType:xMotionEffectType yMotionEffectType:yMotionEffectType];
}
#endif
- (void)updateMotionEffectForXMotionEffectType:(UIInterpolatingMotionEffectType)xMotionEffectType yMotionEffectType:(UIInterpolatingMotionEffectType)yMotionEffectType {
UIInterpolatingMotionEffect *effectX = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:xMotionEffectType];
effectX.minimumRelativeValue = @(-SVProgressHUDParallaxDepthPoints);
effectX.maximumRelativeValue = @(SVProgressHUDParallaxDepthPoints);
UIInterpolatingMotionEffect *effectY = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:yMotionEffectType];
effectY.minimumRelativeValue = @(-SVProgressHUDParallaxDepthPoints);
effectY.maximumRelativeValue = @(SVProgressHUDParallaxDepthPoints);
UIMotionEffectGroup *effectGroup = [UIMotionEffectGroup new];
effectGroup.motionEffects = @[effectX, effectY];
// Clear old motion effect, then add new motion effects
self.hudView.motionEffects = @[];
[self.hudView addMotionEffect:effectGroup];
}
- (void)updateViewHierarchy {
// Add the overlay to the application window if necessary
if(!self.controlView.superview) {
if(self.containerView){
[self.containerView addSubview:self.controlView];
} else {
#if !defined(SV_APP_EXTENSIONS)
[self.frontWindow addSubview:self.controlView];
#else
// If SVProgressHUD ist used inside an app extension add it to the given view
if(self.viewForExtension) {
[self.viewForExtension addSubview:self.controlView];
}
#endif
}
} else {
// The HUD is already on screen, but maybot not in front. Therefore
// ensure that overlay will be on top of rootViewController (which may
// be changed during runtime).
[self.controlView.superview bringSubviewToFront:self.controlView];
}
// Add self to the overlay view
if(!self.superview) {
[self.controlView addSubview:self];
}
}
- (void)setStatus:(NSString*)status {
self.statusLabel.text = status;
[self updateHUDFrame];
}
- (void)setFadeOutTimer:(NSTimer*)timer {
if(_fadeOutTimer) {
[_fadeOutTimer invalidate];
_fadeOutTimer = nil;
}
if(timer) {
_fadeOutTimer = timer;
}
}
#pragma mark - Notifications and their handling
- (void)registerNotifications {
#if TARGET_OS_IOS
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(positionHUD:)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(positionHUD:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(positionHUD:)
name:UIKeyboardDidHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(positionHUD:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(positionHUD:)
name:UIKeyboardDidShowNotification
object:nil];
#endif
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(positionHUD:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
}
- (NSDictionary*)notificationUserInfo {
return (self.statusLabel.text ? @{SVProgressHUDStatusUserInfoKey : self.statusLabel.text} : nil);
}
- (void)positionHUD:(NSNotification*)notification {
CGFloat keyboardHeight = 0.0f;
double animationDuration = 0.0;
#if !defined(SV_APP_EXTENSIONS) && TARGET_OS_IOS
self.frame = [[[UIApplication sharedApplication] delegate] window].bounds;
UIInterfaceOrientation orientation = UIApplication.sharedApplication.statusBarOrientation;
#elif !defined(SV_APP_EXTENSIONS) && !TARGET_OS_IOS
self.frame= [UIApplication sharedApplication].keyWindow.bounds;
#else
if (self.viewForExtension) {
self.frame = self.viewForExtension.frame;
} else {
self.frame = UIScreen.mainScreen.bounds;
}
#if TARGET_OS_IOS
UIInterfaceOrientation orientation = CGRectGetWidth(self.frame) > CGRectGetHeight(self.frame) ? UIInterfaceOrientationLandscapeLeft : UIInterfaceOrientationPortrait;
#endif
#endif
// no transforms applied to window in iOS 8, but only if compiled with iOS 8 sdk as base sdk, otherwise system supports old rotation logic.
BOOL ignoreOrientation = NO;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if([[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {
ignoreOrientation = YES;
}
#endif
#if TARGET_OS_IOS
// Get keyboardHeight in regards to current state
if(notification) {
NSDictionary* keyboardInfo = [notification userInfo];
CGRect keyboardFrame = [keyboardInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
animationDuration = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
if(notification.name == UIKeyboardWillShowNotification || notification.name == UIKeyboardDidShowNotification) {
keyboardHeight = CGRectGetWidth(keyboardFrame);
if(ignoreOrientation || UIInterfaceOrientationIsPortrait(orientation)) {
keyboardHeight = CGRectGetHeight(keyboardFrame);
}
}
} else {
keyboardHeight = self.visibleKeyboardHeight;
}
#endif
// Get the currently active frame of the display (depends on orientation)
CGRect orientationFrame = self.bounds;
#if !defined(SV_APP_EXTENSIONS) && TARGET_OS_IOS
CGRect statusBarFrame = UIApplication.sharedApplication.statusBarFrame;
#else
CGRect statusBarFrame = CGRectZero;
#endif
#if TARGET_OS_IOS
if(!ignoreOrientation && UIInterfaceOrientationIsLandscape(orientation)) {
float temp = CGRectGetWidth(orientationFrame);
orientationFrame.size.width = CGRectGetHeight(orientationFrame);
orientationFrame.size.height = temp;
temp = CGRectGetWidth(statusBarFrame);
statusBarFrame.size.width = CGRectGetHeight(statusBarFrame);
statusBarFrame.size.height = temp;
}
// Update the motion effects in regards to orientation
[self updateMotionEffectForOrientation:orientation];
#else
[self updateMotionEffectForXMotionEffectType:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis yMotionEffectType:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
#endif
// Calculate available height for display
CGFloat activeHeight = CGRectGetHeight(orientationFrame);
if(keyboardHeight > 0) {
activeHeight += CGRectGetHeight(statusBarFrame) * 2;
}
activeHeight -= keyboardHeight;
CGFloat posX = CGRectGetMidX(orientationFrame);
CGFloat posY = floorf(activeHeight*0.45f);
CGFloat rotateAngle = 0.0;
CGPoint newCenter = CGPointMake(posX, posY);
if(notification) {
// Animate update if notification was present
[UIView animateWithDuration:animationDuration
delay:0
options:(UIViewAnimationOptions) (UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState)
animations:^{
[self moveToPoint:newCenter rotateAngle:rotateAngle];
[self.hudView setNeedsDisplay];
} completion:nil];
} else {
[self moveToPoint:newCenter rotateAngle:rotateAngle];
}
}
- (void)moveToPoint:(CGPoint)newCenter rotateAngle:(CGFloat)angle {
self.hudView.transform = CGAffineTransformMakeRotation(angle);
if (self.containerView) {
self.hudView.center = self.containerView.center;
} else {
self.hudView.center = CGPointMake(newCenter.x + self.offsetFromCenter.horizontal, newCenter.y + self.offsetFromCenter.vertical);
}
}
#pragma mark - Event handling
- (void)controlViewDidReceiveTouchEvent:(id)sender forEvent:(UIEvent*)event {
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidReceiveTouchEventNotification
object:self
userInfo:[self notificationUserInfo]];
UITouch *touch = event.allTouches.anyObject;
CGPoint touchLocation = [touch locationInView:self];
if(CGRectContainsPoint(self.hudView.frame, touchLocation)) {
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidTouchDownInsideNotification
object:self
userInfo:[self notificationUserInfo]];
}
}
#pragma mark - Master show/dismiss methods
- (void)showProgress:(float)progress status:(NSString*)status {
__weak SVProgressHUD *weakSelf = self;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
__strong SVProgressHUD *strongSelf = weakSelf;
if(strongSelf){
// Update / Check view hierarchy to ensure the HUD is visible
[strongSelf updateViewHierarchy];
// Reset imageView and fadeout timer if an image is currently displayed
strongSelf.imageView.hidden = YES;
strongSelf.imageView.image = nil;
if(strongSelf.fadeOutTimer) {
strongSelf.activityCount = 0;
}
strongSelf.fadeOutTimer = nil;
// Update text and set progress to the given value
strongSelf.statusLabel.text = status;
strongSelf.progress = progress;
// Choose the "right" indicator depending on the progress
if(progress >= 0) {
// Cancel the indefiniteAnimatedView, then show the ringLayer
[strongSelf cancelIndefiniteAnimatedViewAnimation];
// Add ring to HUD
if(!strongSelf.ringView.superview){
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
[strongSelf.hudVibrancyView.contentView addSubview:strongSelf.ringView];
#else
[strongSelf.hudView addSubview:strongSelf.ringView];
#endif
}
if(!strongSelf.backgroundRingView.superview){
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
[strongSelf.hudVibrancyView.contentView addSubview:strongSelf.backgroundRingView];
#else
[strongSelf.hudView addSubview:strongSelf.backgroundRingView];
#endif
}
// Set progress animated
[CATransaction begin];
[CATransaction setDisableActions:YES];
strongSelf.ringView.strokeEnd = progress;
[CATransaction commit];
// Update the activity count
if(progress == 0) {
strongSelf.activityCount++;
}
} else {
// Cancel the ringLayer animation, then show the indefiniteAnimatedView
[strongSelf cancelRingLayerAnimation];
// Add indefiniteAnimatedView to HUD
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
[strongSelf.hudVibrancyView.contentView addSubview:strongSelf.indefiniteAnimatedView];
#else
[strongSelf.hudView addSubview:strongSelf.indefiniteAnimatedView];
#endif
if([strongSelf.indefiniteAnimatedView respondsToSelector:@selector(startAnimating)]) {
[(id)strongSelf.indefiniteAnimatedView startAnimating];
}
// Update the activity count
strongSelf.activityCount++;
}
// Show
[strongSelf showStatus:status];
}
}];
}
- (void)showImage:(UIImage*)image status:(NSString*)status duration:(NSTimeInterval)duration {
__weak SVProgressHUD *weakSelf = self;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
__strong SVProgressHUD *strongSelf = weakSelf;
if(strongSelf){
// Update / Check view hierarchy to ensure the HUD is visible
[strongSelf updateViewHierarchy];
// Reset progress and cancel any running animation
strongSelf.progress = SVProgressHUDUndefinedProgress;
[strongSelf cancelRingLayerAnimation];
[strongSelf cancelIndefiniteAnimatedViewAnimation];
// Update imageView
UIColor *tintColor = strongSelf.foregroundColorForStyle;
UIImage *tintedImage = image;
if (image.renderingMode != UIImageRenderingModeAlwaysTemplate) {
tintedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
}
strongSelf.imageView.tintColor = tintColor;
strongSelf.imageView.image = tintedImage;
strongSelf.imageView.hidden = NO;
// Update text
strongSelf.statusLabel.text = status;
// Show
[strongSelf showStatus:status];
// An image will dismissed automatically. Therefore we start a timer
// which then will call dismiss after the predefined duration
strongSelf.fadeOutTimer = [NSTimer timerWithTimeInterval:duration target:strongSelf selector:@selector(dismiss) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:strongSelf.fadeOutTimer forMode:NSRunLoopCommonModes];
}
}];
}
- (void)showStatus:(NSString*)status {
// Update the HUDs frame to the new content and position HUD
[self updateHUDFrame];
[self positionHUD:nil];
// Update accessibility as well as user interaction
if(self.defaultMaskType != SVProgressHUDMaskTypeNone) {
self.controlView.userInteractionEnabled = YES;
self.accessibilityLabel = status;
self.isAccessibilityElement = YES;
} else {
self.controlView.userInteractionEnabled = NO;
self.hudView.accessibilityLabel = status;
self.hudView.isAccessibilityElement = YES;
}
// Show if not already visible
// Checking one alpha value is sufficient as they are all the same
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if(self.hudView.contentView.alpha != 1.0f){
#else
if(self.hudView.alpha != 1.0f){
#endif
// Post notification to inform user
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillAppearNotification
object:self
userInfo:[self notificationUserInfo]];
// Zoom HUD a little to make a nice appear / pop up animation
self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 1.3, 1.3);
// Define blocks
__block void (^animationsBlock)(void) = ^{
// Shrink HUD to finish pop up animation
self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 1/1.3f, 1/1.3f);
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
// Fade in effect
UIBlurEffectStyle blurEffectStyle = self.defaultStyle == SVProgressHUDStyleDark ? UIBlurEffectStyleDark : UIBlurEffectStyleExtraLight;
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:blurEffectStyle];
self.hudView.effect = blurEffect;
self.hudVibrancyView.effect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
// Update alpha
self.hudView.contentView.alpha = 1.0f;
#else
self.hudView.alpha = 1.0f;
#endif
self.backgroundView.alpha = 1.0f;
};
__block void (^completionBlock)(void) = ^{
// Check if we really achieved to show the HUD (<=> alpha values are applied)
// and the change of these values has not been cancelled in between e.g. due to a dismissal
// Checking one alpha value is sufficient as they are all the same
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if(self.hudView.contentView.alpha == 1.0f){
#else
if(self.hudView.alpha == 1.0f){
#endif
// Register observer <=> we now have to handle orientation changes etc.
[self registerNotifications];
// Post notification to inform user
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidAppearNotification
object:self
userInfo:[self notificationUserInfo]];
}
// Update accessibility
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, status);
};
if (self.fadeInAnimationDuration > 0) {
// Animate appearance
[UIView animateWithDuration:self.fadeInAnimationDuration
delay:0
options:(UIViewAnimationOptions) (UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState)
animations:^{
animationsBlock();
} completion:^(BOOL finished) {
completionBlock();
}];
} else {
animationsBlock();
completionBlock();
}
// Inform iOS to redraw the view hierarchy
[self setNeedsDisplay];
}
}
- (void)dismiss {
[self dismissWithDelay:0.0 completion:nil];
}
- (void)dismissWithDelay:(NSTimeInterval)delay completion:(SVProgressHUDDismissCompletion)completion {
__weak SVProgressHUD *weakSelf = self;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
__strong SVProgressHUD *strongSelf = weakSelf;
if(strongSelf){
// Post notification to inform user
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillDisappearNotification
object:nil
userInfo:[strongSelf notificationUserInfo]];
// Reset activity count
strongSelf.activityCount = 0;
// Define blocks
__block void (^animationsBlock)(void) = ^{
// Shrink HUD a little to make a nice disappear animation
strongSelf.hudView.transform = CGAffineTransformScale(strongSelf.hudView.transform, 1/1.3f, 1/1.3f);
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
// Fade out effect == remove, and update alpha
strongSelf.hudView.effect = nil;
strongSelf.hudVibrancyView.effect = nil;
strongSelf.hudView.contentView.alpha = 0.0f;
#else
strongSelf.hudView.alpha = 0.0f;
#endif
strongSelf.backgroundView.alpha = 0.0f;
};
__block void (^completionBlock)(void) = ^{
// Check if we really achieved to dismiss the HUD (<=> alpha values are applied)
// and the change of these values has not been cancelled in between e.g. due to a new show
// Checking one alpha value is sufficient as they are all the same
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if(strongSelf.hudView.contentView.alpha == 0.0f){
#else
if(strongSelf.hudView.alpha == 0.0f){
#endif
// Clean up view hierarchy (overlays)
[strongSelf.controlView removeFromSuperview];
[strongSelf.hudView removeFromSuperview];
[strongSelf removeFromSuperview];
// Reset progress and cancel any running animation
strongSelf.progress = SVProgressHUDUndefinedProgress;
[strongSelf cancelRingLayerAnimation];
[strongSelf cancelIndefiniteAnimatedViewAnimation];
// Remove observer <=> we do not have to handle orientation changes etc.
[[NSNotificationCenter defaultCenter] removeObserver:strongSelf];
// Post notification to inform user
[[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidDisappearNotification
object:strongSelf
userInfo:[strongSelf notificationUserInfo]];
// Tell the rootViewController to update the StatusBar appearance
#if !defined(SV_APP_EXTENSIONS) && TARGET_OS_IOS
UIViewController *rootController = [[UIApplication sharedApplication] keyWindow].rootViewController;
[rootController setNeedsStatusBarAppearanceUpdate];
#endif
// Update accessibility
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);
// Run an (optional) completionHandler