-
Notifications
You must be signed in to change notification settings - Fork 1
/
MarqueeLabel.m
executable file
·1501 lines (1207 loc) · 53 KB
/
MarqueeLabel.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
//
// MarqueeLabel.m
//
// Created by Charles Powell on 1/31/11.
// Copyright (c) 2011-2015 Charles Powell. All rights reserved.
//
#import "MarqueeLabel.h"
#import <QuartzCore/QuartzCore.h>
// Notification strings
NSString *const kMarqueeLabelControllerRestartNotification = @"MarqueeLabelViewControllerRestart";
NSString *const kMarqueeLabelShouldLabelizeNotification = @"MarqueeLabelShouldLabelizeNotification";
NSString *const kMarqueeLabelShouldAnimateNotification = @"MarqueeLabelShouldAnimateNotification";
NSString *const kMarqueeLabelAnimationCompletionBlock = @"MarqueeLabelAnimationCompletionBlock";
// Animation completion block
typedef void(^MLAnimationCompletionBlock)(BOOL finished);
// iOS Version check for iOS 8.0.0
#define SYSTEM_VERSION_IS_8_0_X ([[[UIDevice currentDevice] systemVersion] hasPrefix:@"8.0"])
// Helpers
@interface UIView (MarqueeLabelHelpers)
- (UIViewController *)firstAvailableViewController;
- (id)traverseResponderChainForFirstViewController;
@end
@interface CAMediaTimingFunction (MarqueeLabelHelpers)
- (NSArray *)controlPoints;
- (CGFloat)durationPercentageForPositionPercentage:(CGFloat)positionPercentage withDuration:(NSTimeInterval)duration;
@end
@interface MarqueeLabel()
@property (nonatomic, strong) UILabel *subLabel;
@property (nonatomic, assign) NSTimeInterval animationDuration;
@property (nonatomic, assign, readonly) BOOL labelShouldScroll;
@property (nonatomic, weak) UITapGestureRecognizer *tapRecognizer;
@property (nonatomic, assign) CGRect homeLabelFrame;
@property (nonatomic, assign) CGFloat awayOffset;
@property (nonatomic, assign, readwrite) BOOL isPaused;
// Support
@property (nonatomic, strong) NSArray *gradientColors;
CGPoint MLOffsetCGPoint(CGPoint point, CGFloat offset);
@end
@implementation MarqueeLabel
#pragma mark - Class Methods and handlers
+ (void)restartLabelsOfController:(UIViewController *)controller {
[MarqueeLabel notifyController:controller
withMessage:kMarqueeLabelControllerRestartNotification];
}
+ (void)controllerViewWillAppear:(UIViewController *)controller {
[MarqueeLabel restartLabelsOfController:controller];
}
+ (void)controllerViewDidAppear:(UIViewController *)controller {
[MarqueeLabel restartLabelsOfController:controller];
}
+ (void)controllerViewAppearing:(UIViewController *)controller {
[MarqueeLabel restartLabelsOfController:controller];
}
+ (void)controllerLabelsShouldLabelize:(UIViewController *)controller {
[MarqueeLabel notifyController:controller
withMessage:kMarqueeLabelShouldLabelizeNotification];
}
+ (void)controllerLabelsShouldAnimate:(UIViewController *)controller {
[MarqueeLabel notifyController:controller
withMessage:kMarqueeLabelShouldAnimateNotification];
}
+ (void)notifyController:(UIViewController *)controller withMessage:(NSString *)message
{
if (controller && message) {
[[NSNotificationCenter defaultCenter] postNotificationName:message
object:nil
userInfo:[NSDictionary dictionaryWithObject:controller
forKey:@"controller"]];
}
}
- (void)viewControllerShouldRestart:(NSNotification *)notification {
UIViewController *controller = [[notification userInfo] objectForKey:@"controller"];
if (controller == [self firstAvailableViewController]) {
[self restartLabel];
}
}
- (void)labelsShouldLabelize:(NSNotification *)notification {
UIViewController *controller = [[notification userInfo] objectForKey:@"controller"];
if (controller == [self firstAvailableViewController]) {
self.labelize = YES;
}
}
- (void)labelsShouldAnimate:(NSNotification *)notification {
UIViewController *controller = [[notification userInfo] objectForKey:@"controller"];
if (controller == [self firstAvailableViewController]) {
self.labelize = NO;
}
}
#pragma mark - Initialization and Label Config
- (id)initWithFrame:(CGRect)frame {
return [self initWithFrame:frame duration:7.0 andFadeLength:0.0];
}
- (id)initWithFrame:(CGRect)frame duration:(NSTimeInterval)aLengthOfScroll andFadeLength:(CGFloat)aFadeLength {
self = [super initWithFrame:frame];
if (self) {
[self setupLabel];
_scrollDuration = aLengthOfScroll;
self.fadeLength = MIN(aFadeLength, frame.size.width/2);
}
return self;
}
- (id)initWithFrame:(CGRect)frame rate:(CGFloat)pixelsPerSec andFadeLength:(CGFloat)aFadeLength {
self = [super initWithFrame:frame];
if (self) {
[self setupLabel];
_rate = pixelsPerSec;
self.fadeLength = MIN(aFadeLength, frame.size.width/2);
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setupLabel];
if (self.scrollDuration == 0) {
self.scrollDuration = 7.0;
}
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self forwardPropertiesToSubLabel];
}
+ (Class)layerClass {
return [CAReplicatorLayer class];
}
- (CAReplicatorLayer *)repliLayer {
return (CAReplicatorLayer *)self.layer;
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
// Do NOT call super, to prevent UILabel superclass from drawing into context
// Label drawing is handled by sublabel and CAReplicatorLayer layer class
}
- (void)forwardPropertiesToSubLabel {
/*
Note that this method is currently ONLY called from awakeFromNib, i.e. when
text properties are set via a Storyboard. As the Storyboard/IB doesn't currently
support attributed strings, there's no need to "forward" the super attributedString value.
*/
// Since we're a UILabel, we actually do implement all of UILabel's properties.
// We don't care about these values, we just want to forward them on to our sublabel.
NSArray *properties = @[@"baselineAdjustment", @"enabled", @"highlighted", @"highlightedTextColor",
@"minimumFontSize", @"textAlignment",
@"userInteractionEnabled", @"adjustsFontSizeToFitWidth",
@"lineBreakMode", @"numberOfLines"];
// Iterate through properties
self.subLabel.text = super.text;
self.subLabel.font = super.font;
self.subLabel.textColor = super.textColor;
self.subLabel.backgroundColor = (super.backgroundColor == nil ? [UIColor clearColor] : super.backgroundColor);
self.subLabel.shadowColor = super.shadowColor;
self.subLabel.shadowOffset = super.shadowOffset;
for (NSString *property in properties) {
id val = [super valueForKey:property];
[self.subLabel setValue:val forKey:property];
}
}
- (void)setupLabel {
// Basic UILabel options override
self.clipsToBounds = YES;
self.numberOfLines = 1;
// Create first sublabel
self.subLabel = [[UILabel alloc] initWithFrame:self.bounds];
self.subLabel.tag = 700;
self.subLabel.layer.anchorPoint = CGPointMake(0.0f, 0.0f);
[self addSubview:self.subLabel];
// Setup default values
_awayOffset = 0.0f;
_animationCurve = UIViewAnimationOptionCurveLinear;
_labelize = NO;
_holdScrolling = NO;
_tapToScroll = NO;
_isPaused = NO;
_fadeLength = 0.0f;
_animationDelay = 1.0;
_animationDuration = 0.0f;
_leadingBuffer = 0.0f;
_trailingBuffer = 0.0f;
// Add notification observers
// Custom class notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewControllerShouldRestart:) name:kMarqueeLabelControllerRestartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(labelsShouldLabelize:) name:kMarqueeLabelShouldLabelizeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(labelsShouldAnimate:) name:kMarqueeLabelShouldAnimateNotification object:nil];
// UINavigationController view controller change notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observedViewControllerChange:) name:@"UINavigationControllerDidShowViewControllerNotification" object:nil];
// UIApplication state notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restartLabel) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shutdownLabel) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
- (void)observedViewControllerChange:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
id fromController = [userInfo objectForKey:@"UINavigationControllerLastVisibleViewController"];
id toController = [userInfo objectForKey:@"UINavigationControllerNextVisibleViewController"];
id ownController = [self firstAvailableViewController];
if ([fromController isEqual:ownController]) {
[self shutdownLabel];
}
else if ([toController isEqual:ownController]) {
[self restartLabel];
}
}
- (void)minimizeLabelFrameWithMaximumSize:(CGSize)maxSize adjustHeight:(BOOL)adjustHeight {
if (self.subLabel.text != nil) {
// Calculate text size
if (CGSizeEqualToSize(maxSize, CGSizeZero)) {
maxSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
}
CGSize minimumLabelSize = [self subLabelSize];
// Adjust for fade length
CGSize minimumSize = CGSizeMake(minimumLabelSize.width + (self.fadeLength * 2), minimumLabelSize.height);
// Find minimum size of options
minimumSize = CGSizeMake(MIN(minimumSize.width, maxSize.width), MIN(minimumSize.height, maxSize.height));
// Apply to frame
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, minimumSize.width, (adjustHeight ? minimumSize.height : self.frame.size.height));
}
}
-(void)didMoveToSuperview {
[self updateSublabel];
}
#pragma mark - MarqueeLabel Heavy Lifting
- (void)layoutSubviews
{
[super layoutSubviews];
[self updateSublabel];
}
- (void)willMoveToWindow:(UIWindow *)newWindow {
if (!newWindow) {
[self shutdownLabel];
}
}
- (void)didMoveToWindow {
if (self.window) {
[self updateSublabel];
}
}
- (void)updateSublabel {
[self updateSublabelAndBeginScroll:YES];
}
- (void)updateSublabelAndBeginScroll:(BOOL)beginScroll {
if (!self.subLabel.text || !self.superview) {
return;
}
// Calculate expected size
CGSize expectedLabelSize = [self subLabelSize];
// Invalidate intrinsic size
[self invalidateIntrinsicContentSize];
// Move to home
[self returnLabelToOriginImmediately];
// Configure gradient for the current condition
[self applyGradientMaskForFadeLength:self.fadeLength animated:YES];
// Check if label should scroll
// Can be because: 1) text fits, or 2) labelization
// The holdScrolling property does NOT affect this
if (!self.labelShouldScroll) {
// Set text alignment and break mode to act like normal label
self.subLabel.textAlignment = [super textAlignment];
self.subLabel.lineBreakMode = [super lineBreakMode];
CGRect labelFrame, unusedFrame;
switch (self.marqueeType) {
case MLContinuousReverse:
case MLRightLeft:
CGRectDivide(self.bounds, &unusedFrame, &labelFrame, self.leadingBuffer, CGRectMaxXEdge);
labelFrame = CGRectIntegral(labelFrame);
break;
default:
labelFrame = CGRectIntegral(CGRectMake(self.leadingBuffer, 0.0f, self.bounds.size.width - self.leadingBuffer, self.bounds.size.height));
break;
}
self.homeLabelFrame = labelFrame;
self.awayOffset = 0.0f;
// Remove an additional sublabels (for continuous types)
self.repliLayer.instanceCount = 1;
// Set sublabel frame calculated labelFrame
self.subLabel.frame = labelFrame;
return;
}
// Label DOES need to scroll
[self.subLabel setLineBreakMode:NSLineBreakByClipping];
// Spacing between primary and second sublabel must be at least equal to leadingBuffer, and at least equal to the fadeLength
CGFloat minTrailing = MAX(MAX(self.leadingBuffer, self.trailingBuffer), self.fadeLength);
switch (self.marqueeType) {
case MLContinuous:
case MLContinuousReverse:
{
if (self.marqueeType == MLContinuous) {
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.leadingBuffer, 0.0f, expectedLabelSize.width, self.bounds.size.height));
self.awayOffset = -(self.homeLabelFrame.size.width + minTrailing);
} else {
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.bounds.size.width - (expectedLabelSize.width + self.leadingBuffer), 0.0f, expectedLabelSize.width, self.bounds.size.height));
self.awayOffset = (self.homeLabelFrame.size.width + minTrailing);
}
self.subLabel.frame = self.homeLabelFrame;
// Configure replication
self.repliLayer.instanceCount = 2;
self.repliLayer.instanceTransform = CATransform3DMakeTranslation(-self.awayOffset, 0.0, 0.0);
// Recompute the animation duration
self.animationDuration = (self.rate != 0) ? ((NSTimeInterval) fabs(self.awayOffset) / self.rate) : (self.scrollDuration);
break;
}
case MLRightLeft:
{
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.bounds.size.width - (expectedLabelSize.width + self.leadingBuffer), 0.0f, expectedLabelSize.width, self.bounds.size.height));
self.awayOffset = (expectedLabelSize.width + self.trailingBuffer + self.leadingBuffer) - self.bounds.size.width;
// Calculate animation duration
self.animationDuration = (self.rate != 0) ? (NSTimeInterval)fabs(self.awayOffset / self.rate) : (self.scrollDuration);
// Set frame and text
self.subLabel.frame = self.homeLabelFrame;
// Remove any replication
self.repliLayer.instanceCount = 1;
// Enforce text alignment for this type
self.subLabel.textAlignment = NSTextAlignmentRight;
break;
}
case MLLeftRight:
{
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.leadingBuffer, 0.0f, expectedLabelSize.width, expectedLabelSize.height));
self.awayOffset = self.bounds.size.width - (expectedLabelSize.width + self.leadingBuffer + self.trailingBuffer);
// Calculate animation duration
self.animationDuration = (self.rate != 0) ? (NSTimeInterval)fabs(self.awayOffset / self.rate) : (self.scrollDuration);
// Set frame
self.subLabel.frame = self.homeLabelFrame;
// Remove any replication
self.repliLayer.instanceCount = 1;
// Enforce text alignment for this type
self.subLabel.textAlignment = NSTextAlignmentLeft;
break;
}
default:
{
// Something strange has happened
self.homeLabelFrame = CGRectZero;
self.awayOffset = 0.0f;
// Do not attempt to begin scroll
return;
break;
}
} //end of marqueeType switch
if (!self.tapToScroll && !self.holdScrolling && beginScroll) {
[self beginScroll];
}
}
- (CGSize)subLabelSize {
// Calculate expected size
CGSize expectedLabelSize = CGSizeZero;
CGSize maximumLabelSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
// Get size of subLabel
expectedLabelSize = [self.subLabel sizeThatFits:maximumLabelSize];
// Sanitize width to 5461.0f (largest width a UILabel will draw on an iPhone 6S Plus)
expectedLabelSize.width = MIN(expectedLabelSize.width, 5461.0f);
// Adjust to own height (make text baseline match normal label)
expectedLabelSize.height = self.bounds.size.height;
return expectedLabelSize;
}
- (CGSize)sizeThatFits:(CGSize)size {
CGSize fitSize = [self.subLabel sizeThatFits:size];
fitSize.width += self.leadingBuffer;
return fitSize;
}
#pragma mark - Animation Handlers
- (BOOL)labelShouldScroll {
BOOL stringLength = ([self.subLabel.text length] > 0);
if (!stringLength) {
return NO;
}
BOOL labelTooLarge = ([self subLabelSize].width + self.leadingBuffer > self.bounds.size.width);
return (!self.labelize && labelTooLarge);
}
- (BOOL)labelReadyForScroll {
// Check if we have a superview
if (!self.superview) {
return NO;
}
if (!self.window) {
return NO;
}
// Check if our view controller is ready
UIViewController *viewController = [self firstAvailableViewController];
if (!viewController.isViewLoaded) {
return NO;
}
return YES;
}
- (void)beginScroll {
[self beginScrollWithDelay:YES];
}
- (void)beginScrollWithDelay:(BOOL)delay {
switch (self.marqueeType) {
case MLContinuous:
case MLContinuousReverse:
[self scrollContinuousWithInterval:self.animationDuration after:(delay ? self.animationDelay : 0.0)];
break;
default:
[self scrollAwayWithInterval:self.animationDuration];
break;
}
}
- (void)returnLabelToOriginImmediately {
// Remove gradient animations
[self.layer.mask removeAllAnimations];
// Remove sublabel position animations
[self.subLabel.layer removeAllAnimations];
}
- (void)scrollAwayWithInterval:(NSTimeInterval)interval {
[self scrollAwayWithInterval:interval delay:YES];
}
- (void)scrollAwayWithInterval:(NSTimeInterval)interval delay:(BOOL)delay {
[self scrollAwayWithInterval:interval delayAmount:(delay ? self.animationDelay : 0.0)];
}
- (void)scrollAwayWithInterval:(NSTimeInterval)interval delayAmount:(NSTimeInterval)delayAmount {
// Check for conditions which would prevent scrolling
if (![self labelReadyForScroll]) {
return;
}
// Return labels to home (cancel any animations)
[self returnLabelToOriginImmediately];
// Call pre-animation method
[self labelWillBeginScroll];
// Animate
[CATransaction begin];
// Set Duration
[CATransaction setAnimationDuration:(2.0 * (delayAmount + interval))];
// Create animation for gradient, if needed
if (self.fadeLength != 0.0f) {
CAKeyframeAnimation *gradAnim = [self keyFrameAnimationForGradientFadeLength:self.fadeLength
interval:interval
delay:delayAmount];
[self.layer.mask addAnimation:gradAnim forKey:@"gradient"];
}
MLAnimationCompletionBlock completionBlock = ^(BOOL finished) {
if (!finished) {
// Do not continue into the next loop
return;
}
// Call returned home method
[self labelReturnedToHome:YES];
// Check to ensure that:
// 1) We don't double fire if an animation already exists
// 2) The instance is still attached to a window - this completion block is called for
// many reasons, including if the animation is removed due to the view being removed
// from the UIWindow (typically when the view controller is no longer the "top" view)
if (self.window && ![self.subLabel.layer animationForKey:@"position"]) {
// Begin again, if conditions met
if (self.labelShouldScroll && !self.tapToScroll && !self.holdScrolling) {
[self scrollAwayWithInterval:interval delayAmount:delayAmount];
}
}
};
// Create animation for position
CGPoint homeOrigin = self.homeLabelFrame.origin;
CGPoint awayOrigin = MLOffsetCGPoint(self.homeLabelFrame.origin, self.awayOffset);
NSArray *values = @[[NSValue valueWithCGPoint:homeOrigin], // Initial location, home
[NSValue valueWithCGPoint:homeOrigin], // Initial delay, at home
[NSValue valueWithCGPoint:awayOrigin], // Animation to away
[NSValue valueWithCGPoint:awayOrigin], // Delay at away
[NSValue valueWithCGPoint:homeOrigin]]; // Animation to home
CAKeyframeAnimation *awayAnim = [self keyFrameAnimationForProperty:@"position"
values:values
interval:interval
delay:delayAmount];
// Add completion block
[awayAnim setValue:completionBlock forKey:kMarqueeLabelAnimationCompletionBlock];
// Add animation
[self.subLabel.layer addAnimation:awayAnim forKey:@"position"];
[CATransaction commit];
}
- (void)scrollContinuousWithInterval:(NSTimeInterval)interval after:(NSTimeInterval)delayAmount {
// Check for conditions which would prevent scrolling
if (![self labelReadyForScroll]) {
return;
}
// Return labels to home (cancel any animations)
[self returnLabelToOriginImmediately];
// Call pre-animation method
[self labelWillBeginScroll];
// Animate
[CATransaction begin];
// Set Duration
[CATransaction setAnimationDuration:(delayAmount + interval)];
// Create animation for gradient, if needed
if (self.fadeLength != 0.0f) {
CAKeyframeAnimation *gradAnim = [self keyFrameAnimationForGradientFadeLength:self.fadeLength
interval:interval
delay:delayAmount];
[self.layer.mask addAnimation:gradAnim forKey:@"gradient"];
}
MLAnimationCompletionBlock completionBlock = ^(BOOL finished) {
if (!finished) {
// Do not continue into the next loop
return;
}
// Call returned home method
[self labelReturnedToHome:YES];
// Check to ensure that:
// 1) We don't double fire if an animation already exists
// 2) The instance is still attached to a window - this completion block is called for
// many reasons, including if the animation is removed due to the view being removed
// from the UIWindow (typically when the view controller is no longer the "top" view)
if (self.window && ![self.subLabel.layer animationForKey:@"position"]) {
// Begin again, if conditions met
if (self.labelShouldScroll && !self.tapToScroll && !self.holdScrolling) {
[self scrollContinuousWithInterval:interval after:delayAmount];
}
}
};
// Create animation for sublabel positions
CGPoint homeOrigin = self.homeLabelFrame.origin;
CGPoint awayOrigin = MLOffsetCGPoint(self.homeLabelFrame.origin, self.awayOffset);
NSArray *values = @[[NSValue valueWithCGPoint:homeOrigin], // Initial location, home
[NSValue valueWithCGPoint:homeOrigin], // Initial delay, at home
[NSValue valueWithCGPoint:awayOrigin]]; // Animation to home
CAKeyframeAnimation *awayAnim = [self keyFrameAnimationForProperty:@"position"
values:values
interval:interval
delay:delayAmount];
// Attach completion block
[awayAnim setValue:completionBlock forKey:kMarqueeLabelAnimationCompletionBlock];
// Add animation
[self.subLabel.layer addAnimation:awayAnim forKey:@"position"];
[CATransaction commit];
}
- (void)applyGradientMaskForFadeLength:(CGFloat)fadeLength animated:(BOOL)animated {
// Check for zero-length fade
if (fadeLength <= 0.0f) {
[self removeGradientMask];
return;
}
CAGradientLayer *gradientMask = (CAGradientLayer *)self.layer.mask;
[gradientMask removeAllAnimations];
if (!gradientMask) {
// Create CAGradientLayer if needed
gradientMask = [CAGradientLayer layer];
}
// Set up colors
NSObject *transparent = (NSObject *)[[UIColor clearColor] CGColor];
NSObject *opaque = (NSObject *)[[UIColor blackColor] CGColor];
gradientMask.bounds = self.layer.bounds;
gradientMask.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
gradientMask.shouldRasterize = YES;
gradientMask.rasterizationScale = [UIScreen mainScreen].scale;
gradientMask.startPoint = CGPointMake(0.0f, 0.5f);
gradientMask.endPoint = CGPointMake(1.0f, 0.5f);
// Start with "no fade" colors and locations
gradientMask.colors = @[opaque, opaque, opaque, opaque];
gradientMask.locations = @[@(0.0f), @(0.0f), @(1.0f), @(1.0f)];
// Set mask
self.layer.mask = gradientMask;
CGFloat leftFadeStop = fadeLength/self.bounds.size.width;
CGFloat rightFadeStop = fadeLength/self.bounds.size.width;
// Adjust stops based on fade length
NSArray *adjustedLocations = @[@(0.0), @(leftFadeStop), @(1.0 - rightFadeStop), @(1.0)];
// Determine colors for non-scrolling label (i.e. at home)
NSArray *adjustedColors;
BOOL trailingFadeNeeded = self.labelShouldScroll;
switch (self.marqueeType) {
case MLContinuousReverse:
case MLRightLeft:
adjustedColors = @[(trailingFadeNeeded ? transparent : opaque),
opaque,
opaque,
opaque];
break;
default:
// MLContinuous
// MLLeftRight
adjustedColors = @[opaque,
opaque,
opaque,
(trailingFadeNeeded ? transparent : opaque)];
break;
}
if (animated) {
// Create animation for location change
CABasicAnimation *locationAnimation = [CABasicAnimation animationWithKeyPath:@"locations"];
locationAnimation.fromValue = gradientMask.locations;
locationAnimation.toValue = adjustedLocations;
locationAnimation.duration = 0.25;
// Create animation for color change
CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"colors"];
colorAnimation.fromValue = gradientMask.colors;
colorAnimation.toValue = adjustedColors;
colorAnimation.duration = 0.25;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = 0.25;
group.animations = @[locationAnimation, colorAnimation];
[gradientMask addAnimation:group forKey:colorAnimation.keyPath];
gradientMask.locations = adjustedLocations;
gradientMask.colors = adjustedColors;
} else {
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
gradientMask.locations = adjustedLocations;
gradientMask.colors = adjustedColors;
[CATransaction commit];
}
}
- (void)removeGradientMask {
self.layer.mask = nil;
}
- (CAKeyframeAnimation *)keyFrameAnimationForGradientFadeLength:(CGFloat)fadeLength
interval:(NSTimeInterval)interval
delay:(NSTimeInterval)delayAmount
{
// Setup
NSArray *values = nil;
NSArray *keyTimes = nil;
NSTimeInterval totalDuration;
NSObject *transp = (NSObject *)[[UIColor clearColor] CGColor];
NSObject *opaque = (NSObject *)[[UIColor blackColor] CGColor];
// Create new animation
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"colors"];
// Get timing function
CAMediaTimingFunction *timingFunction = [self timingFunctionForAnimationOptions:self.animationCurve];
// Define keyTimes
switch (self.marqueeType) {
case MLLeftRight:
case MLRightLeft:
// Calculate total animation duration
totalDuration = 2.0 * (delayAmount + interval);
keyTimes = @[
@(0.0), // 1) Initial gradient
@(delayAmount/totalDuration), // 2) Begin of LE fade-in, just as scroll away starts
@((delayAmount + 0.4)/totalDuration), // 3) End of LE fade in [LE fully faded]
@((delayAmount + interval - 0.4)/totalDuration), // 4) Begin of TE fade out, just before scroll away finishes
@((delayAmount + interval)/totalDuration), // 5) End of TE fade out [TE fade removed]
@((delayAmount + interval + delayAmount)/totalDuration), // 6) Begin of TE fade back in, just as scroll home starts
@((delayAmount + interval + delayAmount + 0.4)/totalDuration), // 7) End of TE fade back in [TE fully faded]
@((totalDuration - 0.4)/totalDuration), // 8) Begin of LE fade out, just before scroll home finishes
@(1.0)]; // 9) End of LE fade out, just as scroll home finishes
break;
case MLContinuousReverse:
default:
// Calculate total animation duration
totalDuration = delayAmount + interval;
// Find when the lead label will be totally offscreen
CGFloat startFadeFraction = fabs((self.subLabel.bounds.size.width + self.leadingBuffer) / self.awayOffset);
// Find when the animation will hit that point
CGFloat startFadeTimeFraction = [timingFunction durationPercentageForPositionPercentage:startFadeFraction withDuration:totalDuration];
NSTimeInterval startFadeTime = delayAmount + startFadeTimeFraction * interval;
keyTimes = @[
@(0.0), // Initial gradient
@(delayAmount/totalDuration), // Begin of fade in
@((delayAmount + 0.2)/totalDuration), // End of fade in, just as scroll away starts
@((startFadeTime)/totalDuration), // Begin of fade out, just before scroll home completes
@((startFadeTime + 0.1)/totalDuration), // End of fade out, as scroll home completes
@(1.0) // Buffer final value (used on continuous types)
];
break;
}
// Define gradient values
switch (self.marqueeType) {
case MLContinuousReverse:
values = @[
@[transp, opaque, opaque, opaque], // Initial gradient
@[transp, opaque, opaque, opaque], // Begin of fade in
@[transp, opaque, opaque, transp], // End of fade in, just as scroll away starts
@[transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes
@[transp, opaque, opaque, opaque], // End of fade out, as scroll home completes
@[transp, opaque, opaque, opaque] // Final "home" value
];
break;
case MLRightLeft:
values = @[
@[transp, opaque, opaque, opaque], // 1)
@[transp, opaque, opaque, opaque], // 2)
@[transp, opaque, opaque, transp], // 3)
@[transp, opaque, opaque, transp], // 4)
@[opaque, opaque, opaque, transp], // 5)
@[opaque, opaque, opaque, transp], // 6)
@[transp, opaque, opaque, transp], // 7)
@[transp, opaque, opaque, transp], // 8)
@[transp, opaque, opaque, opaque] // 9)
];
break;
case MLContinuous:
values = @[
@[opaque, opaque, opaque, transp], // Initial gradient
@[opaque, opaque, opaque, transp], // Begin of fade in
@[transp, opaque, opaque, transp], // End of fade in, just as scroll away starts
@[transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes
@[opaque, opaque, opaque, transp], // End of fade out, as scroll home completes
@[opaque, opaque, opaque, transp] // Final "home" value
];
break;
case MLLeftRight:
default:
values = @[
@[opaque, opaque, opaque, transp], // 1)
@[opaque, opaque, opaque, transp], // 2)
@[transp, opaque, opaque, transp], // 3)
@[transp, opaque, opaque, transp], // 4)
@[transp, opaque, opaque, opaque], // 5)
@[transp, opaque, opaque, opaque], // 6)
@[transp, opaque, opaque, transp], // 7)
@[transp, opaque, opaque, transp], // 8)
@[opaque, opaque, opaque, transp] // 9)
];
break;
}
animation.values = values;
animation.keyTimes = keyTimes;
animation.timingFunctions = @[timingFunction, timingFunction, timingFunction, timingFunction];
return animation;
}
- (CAKeyframeAnimation *)keyFrameAnimationForProperty:(NSString *)property
values:(NSArray *)values
interval:(NSTimeInterval)interval
delay:(NSTimeInterval)delayAmount
{
// Create new animation
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:property];
// Get timing function
CAMediaTimingFunction *timingFunction = [self timingFunctionForAnimationOptions:self.animationCurve];
// Calculate times based on marqueeType
NSTimeInterval totalDuration;
switch (self.marqueeType) {
case MLLeftRight:
case MLRightLeft:
NSAssert(values.count == 5, @"Incorrect number of values passed for MLLeftRight-type animation");
totalDuration = 2.0 * (delayAmount + interval);
// Set up keyTimes
animation.keyTimes = @[@(0.0), // Initial location, home
@(delayAmount/totalDuration), // Initial delay, at home
@((delayAmount + interval)/totalDuration), // Animation to away
@((delayAmount + interval + delayAmount)/totalDuration), // Delay at away
@(1.0)]; // Animation to home
animation.timingFunctions = @[timingFunction,
timingFunction,
timingFunction,
timingFunction];
break;
// MLContinuous
// MLContinuousReverse
default:
NSAssert(values.count == 3, @"Incorrect number of values passed for MLContinous-type animation");
totalDuration = delayAmount + interval;
// Set up keyTimes
animation.keyTimes = @[@(0.0), // Initial location, home
@(delayAmount/totalDuration), // Initial delay, at home
@(1.0)]; // Animation to away
animation.timingFunctions = @[timingFunction,
timingFunction];
break;
}
// Set values
animation.values = values;
animation.delegate = self;
return animation;
}
- (CAMediaTimingFunction *)timingFunctionForAnimationOptions:(UIViewAnimationOptions)animationOptions {
NSString *timingFunction;
switch (animationOptions) {
case UIViewAnimationOptionCurveEaseIn:
timingFunction = kCAMediaTimingFunctionEaseIn;
break;
case UIViewAnimationOptionCurveEaseInOut:
timingFunction = kCAMediaTimingFunctionEaseInEaseOut;
break;
case UIViewAnimationOptionCurveEaseOut:
timingFunction = kCAMediaTimingFunctionEaseOut;
break;
default:
timingFunction = kCAMediaTimingFunctionLinear;
break;
}
return [CAMediaTimingFunction functionWithName:timingFunction];
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
MLAnimationCompletionBlock completionBlock = [anim valueForKey:kMarqueeLabelAnimationCompletionBlock];
if (completionBlock) {
completionBlock(flag);
}
}
#pragma mark - Label Control
- (void)restartLabel {
// Shutdown the label
[self shutdownLabel];
// Restart scrolling if appropriate
if (self.labelShouldScroll && !self.tapToScroll && !self.holdScrolling) {
[self beginScroll];
}
}
- (void)resetLabel {
[self returnLabelToOriginImmediately];
self.homeLabelFrame = CGRectNull;
self.awayOffset = 0.0f;
}
- (void)shutdownLabel {
// Bring label to home location
[self returnLabelToOriginImmediately];
// Apply gradient mask for home location
[self applyGradientMaskForFadeLength:self.fadeLength animated:false];
}
-(void)pauseLabel
{
// Only pause if label is not already paused, and already in a scrolling animation
if (!self.isPaused && self.awayFromHome) {
// Pause sublabel position animation
CFTimeInterval labelPauseTime = [self.subLabel.layer convertTime:CACurrentMediaTime() fromLayer:nil];
self.subLabel.layer.speed = 0.0;
self.subLabel.layer.timeOffset = labelPauseTime;
// Pause gradient fade animation
CFTimeInterval gradientPauseTime = [self.layer.mask convertTime:CACurrentMediaTime() fromLayer:nil];
self.layer.mask.speed = 0.0;
self.layer.mask.timeOffset = gradientPauseTime;
self.isPaused = YES;
}
}
-(void)unpauseLabel
{