forked from cbpowell/MarqueeLabel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MarqueeLabel.m
executable file
·1097 lines (870 loc) · 39.3 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
//
#import "MarqueeLabel.h"
#import <QuartzCore/QuartzCore.h>
NSString *const kMarqueeLabelControllerRestartNotification = @"MarqueeLabelViewControllerRestart";
NSString *const kMarqueeLabelShouldLabelizeNotification = @"MarqueeLabelShouldLabelizeNotification";
NSString *const kMarqueeLabelShouldAnimateNotification = @"MarqueeLabelShouldAnimateNotification";
typedef void (^animationCompletionBlock)(void);
// Helpers
@interface UIView (MarqueeLabelHelpers)
- (UIViewController *)firstAvailableViewController;
- (id)traverseResponderChainForFirstViewController;
@end
@interface MarqueeLabel()
@property (nonatomic, strong) UILabel *subLabel;
@property (nonatomic, assign, readwrite) BOOL awayFromHome;
@property (nonatomic, assign) BOOL orientationWillChange;
@property (nonatomic, strong) id orientationObserver;
@property (nonatomic, assign) NSTimeInterval animationDuration;
@property (nonatomic, assign, readonly) BOOL labelShouldScroll;
@property (nonatomic, weak) UITapGestureRecognizer *tapRecognizer;
@property (nonatomic, assign) CGRect homeLabelFrame;
@property (nonatomic, assign) CGRect awayLabelFrame;
@property (nonatomic, assign, readwrite) BOOL isPaused;
- (void)scrollAwayWithInterval:(NSTimeInterval)interval;
- (void)scrollHomeWithInterval:(NSTimeInterval)interval;
- (void)returnLabelToOriginImmediately;
- (void)restartLabel;
- (void)setupLabel;
- (void)observedViewControllerChange:(NSNotification *)notification;
- (void)applyGradientMaskForFadeLength:(CGFloat)fadeLength;
- (void)applyGradientMaskForFadeLength:(CGFloat)fadeLength animated:(BOOL)animated;
- (NSArray *)allSubLabels;
// Support
@property (nonatomic, strong) NSArray *gradientColors;
@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];
_lengthOfScroll = 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.lengthOfScroll == 0) {
self.lengthOfScroll = 7.0;
}
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self forwardPropertiesToSubLabel];
}
- (void)forwardPropertiesToSubLabel {
// 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", @"font", @"highlighted", @"highlightedTextColor", @"minimumFontSize", @"shadowColor", @"shadowOffset", @"textAlignment", @"textColor", @"userInteractionEnabled", @"text", @"adjustsFontSizeToFitWidth", @"lineBreakMode", @"numberOfLines", @"backgroundColor"];
for (NSString *property in properties) {
id val = [super valueForKey:property];
[self.subLabel setValue:val forKey:property];
}
[self setText:[super text]];
[self setFont:[super font]];
}
- (void)setupLabel {
// Basic UILabel options override
self.clipsToBounds = YES;
self.numberOfLines = 1;
self.subLabel = [[UILabel alloc] initWithFrame:self.bounds];
self.subLabel.tag = 700;
[self addSubview:self.subLabel];
[super setBackgroundColor:[UIColor clearColor]];
_animationCurve = UIViewAnimationOptionCurveEaseInOut;
_awayFromHome = NO;
_orientationWillChange = NO;
_labelize = NO;
_holdScrolling = NO;
_tapToScroll = NO;
_isPaused = NO;
_fadeLength = 0.0f;
_animationDelay = 1.0;
_animationDuration = 0.0f;
_continuousMarqueeExtraBuffer = 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:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restartLabel) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shutdownLabel) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shutdownLabel) name:UIApplicationDidEnterBackgroundNotification object:nil];
// Device Orientation change handling
/* Necessary to prevent a "super-speed" scroll bug. When the frame is changed due to a flexible width autoresizing mask,
* the setFrame call occurs during the in-flight orientation rotation animation, and the scroll to the away location
* occurs at super speed. To work around this, the orientationWilLChange property is set to YES when the notification
* UIApplicationWillChangeStatusBarOrientationNotification is posted, and a notification handler block listening for
* the UIViewAnimationDidStopNotification notification is added. The handler block checks the notification userInfo to
* see if the delegate of the ending animation is the UIWindow of the label. If so, the rotation animation has finished
* and the label can be restarted, and the notification observer removed.
*/
__weak __typeof(&*self)weakSelf = self;
__block id animationObserver = nil;
self.orientationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillChangeStatusBarOrientationNotification
object:nil
queue:nil
usingBlock:^(NSNotification *notification){
weakSelf.orientationWillChange = YES;
[weakSelf returnLabelToOriginImmediately];
animationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:@"UIViewAnimationDidStopNotification"
object:nil
queue:nil
usingBlock:^(NSNotification *notification){
if ([notification.userInfo objectForKey:@"delegate"] == weakSelf.window) {
weakSelf.orientationWillChange = NO;
[weakSelf restartLabel];
// Remove notification observer
[[NSNotificationCenter defaultCenter] removeObserver:animationObserver];
}
}];
}];
}
- (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 updateSublabelAndLocationsAndBeginScroll:YES];
}
#pragma mark - MarqueeLabel Heavy Lifting
- (void)updateSublabelAndLocations {
[self updateSublabelAndLocationsAndBeginScroll:YES];
}
- (void)updateSublabelAndLocationsAndBeginScroll:(BOOL)beginScroll {
if (!self.subLabel.text) {
return;
}
// Calculate expected size
CGSize expectedLabelSize = [self subLabelSize];
// Invalidate intrinsic size
if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) {
[self invalidateIntrinsicContentSize];
}
// Move to origin
[self returnLabelToOriginImmediately];
// Check if label is labelized, or does not need to scroll
if (self.labelize || !self.labelShouldScroll) {
// Set text alignment and break mode to act like normal label
[self.subLabel setTextAlignment:[super textAlignment]];
[self.subLabel setLineBreakMode:[super lineBreakMode]];
CGRect labelFrame = CGRectIntegral(CGRectMake(self.fadeLength, 0.0f, self.bounds.size.width - self.fadeLength * 2.0f, expectedLabelSize.height));
self.homeLabelFrame = labelFrame;
self.awayLabelFrame = labelFrame;
// Remove any additional text layers (for MLContinuous)
NSArray *labels = [self allSubLabels];
for (UILabel *sl in labels) {
if (sl != self.subLabel) {
[sl removeFromSuperview];
}
}
self.subLabel.frame = self.homeLabelFrame;
return;
}
// Label does need to scroll
[self.subLabel setLineBreakMode:NSLineBreakByClipping];
switch (self.marqueeType) {
case MLContinuous:
{
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.fadeLength, 0.0f, expectedLabelSize.width, expectedLabelSize.height));
CGFloat awayLabelOffset = -(self.homeLabelFrame.size.width + 2 * self.fadeLength + self.continuousMarqueeExtraBuffer);
self.awayLabelFrame = CGRectIntegral(CGRectOffset(self.homeLabelFrame, awayLabelOffset, 0.0f));
NSArray *labels = [self allSubLabels];
if (labels.count < 2) {
UILabel *secondSubLabel = [[UILabel alloc] initWithFrame:CGRectOffset(self.homeLabelFrame, self.homeLabelFrame.size.width + self.fadeLength + self.continuousMarqueeExtraBuffer, 0.0f)];
secondSubLabel.tag = 701;
secondSubLabel.numberOfLines = 1;
[self addSubview:secondSubLabel];
labels = [labels arrayByAddingObject:secondSubLabel];
}
[self refreshSubLabels:labels];
// Recompute the animation duration
self.animationDuration = (self.rate != 0) ? ((NSTimeInterval) fabs(self.awayLabelFrame.origin.x) / self.rate) : (self.lengthOfScroll);
self.subLabel.frame = self.homeLabelFrame;
break;
}
case MLContinuousReverse:
{
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.bounds.size.width - (expectedLabelSize.width + self.fadeLength), 0.0f, expectedLabelSize.width, expectedLabelSize.height));
CGFloat awayLabelOffset = (self.homeLabelFrame.size.width + 2 * self.fadeLength + self.continuousMarqueeExtraBuffer);
self.awayLabelFrame = CGRectIntegral(CGRectOffset(self.homeLabelFrame, awayLabelOffset, 0.0f));
NSArray *labels = [self allSubLabels];
if (labels.count < 2) {
UILabel *secondSubLabel = [[UILabel alloc] initWithFrame:CGRectOffset(self.homeLabelFrame, -(self.homeLabelFrame.size.width + self.fadeLength + self.continuousMarqueeExtraBuffer), 0.0f)];
secondSubLabel.numberOfLines = 1;
secondSubLabel.tag = 701;
[self addSubview:secondSubLabel];
labels = [labels arrayByAddingObject:secondSubLabel];
}
[self refreshSubLabels:labels];
// Recompute the animation duration
self.animationDuration = (self.rate != 0) ? ((NSTimeInterval) fabs(self.awayLabelFrame.origin.x) / self.rate) : (self.lengthOfScroll);
self.subLabel.frame = self.homeLabelFrame;
break;
}
case MLRightLeft:
{
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.bounds.size.width - (expectedLabelSize.width + self.fadeLength), 0.0f, expectedLabelSize.width, expectedLabelSize.height));
self.awayLabelFrame = CGRectIntegral(CGRectMake(self.fadeLength, 0.0f, expectedLabelSize.width, expectedLabelSize.height));
// Calculate animation duration
self.animationDuration = (self.rate != 0) ? ((NSTimeInterval)fabs(self.awayLabelFrame.origin.x - self.homeLabelFrame.origin.x) / self.rate) : (self.lengthOfScroll);
// Set frame and text
self.subLabel.frame = self.homeLabelFrame;
// Enforce text alignment for this type
self.subLabel.textAlignment = NSTextAlignmentRight;
break;
}
//Fallback to LeftRight marqueeType
default:
{
self.homeLabelFrame = CGRectIntegral(CGRectMake(self.fadeLength, 0.0f, expectedLabelSize.width, expectedLabelSize.height));
self.awayLabelFrame = CGRectIntegral(CGRectOffset(self.homeLabelFrame, -expectedLabelSize.width + (self.bounds.size.width - self.fadeLength * 2), 0.0));
// Calculate animation duration
self.animationDuration = (self.rate != 0) ? ((NSTimeInterval)fabs(self.awayLabelFrame.origin.x - self.homeLabelFrame.origin.x) / self.rate) : (self.lengthOfScroll);
// Set frame
self.subLabel.frame = self.homeLabelFrame;
// Enforce text alignment for this type
self.subLabel.textAlignment = NSTextAlignmentLeft;
}
} //end of marqueeType switch
if (!self.tapToScroll && !self.holdScrolling && beginScroll) {
[self beginScroll];
}
}
- (void)applyGradientMaskForFadeLength:(CGFloat)fadeLength {
[self applyGradientMaskForFadeLength:fadeLength animated:YES];
}
- (void)applyGradientMaskForFadeLength:(CGFloat)fadeLength animated:(BOOL)animated {
if (animated) {
[self returnLabelToOriginImmediately];
}
CAGradientLayer *gradientMask = nil;
if (fadeLength != 0.0f) {
// Recreate gradient mask with new fade length
gradientMask = [CAGradientLayer layer];
gradientMask.bounds = self.layer.bounds;
gradientMask.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
gradientMask.shouldRasterize = YES;
gradientMask.rasterizationScale = [UIScreen mainScreen].scale;
gradientMask.startPoint = CGPointMake(0.0, CGRectGetMidY(self.frame));
gradientMask.endPoint = CGPointMake(1.0, CGRectGetMidY(self.frame));
CGFloat fadePoint = (CGFloat)self.fadeLength/self.frame.size.width;
[gradientMask setColors:self.gradientColors];
[gradientMask setLocations: [NSArray arrayWithObjects:
[NSNumber numberWithDouble: 0.0],
[NSNumber numberWithDouble: fadePoint],
[NSNumber numberWithDouble: 1 - fadePoint],
[NSNumber numberWithDouble: 1.0],
nil]];
}
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
self.layer.mask = gradientMask;
[CATransaction commit];
if (animated && self.labelShouldScroll && !self.tapToScroll) {
[self beginScroll];
}
}
- (CGSize)subLabelSize {
// Calculate expected size
CGSize expectedLabelSize = CGSizeZero;
CGSize maximumLabelSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
// Check for attributed string attributes
if ([self.subLabel respondsToSelector:@selector(attributedText)]) {
// Calculate based on attributed text
expectedLabelSize = [self.subLabel.attributedText boundingRectWithSize:maximumLabelSize
options:0
context:nil].size;
} else {
// Calculate on base string
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
expectedLabelSize = [self.subLabel.text sizeWithFont:self.font
constrainedToSize:maximumLabelSize
lineBreakMode:NSLineBreakByClipping];
#endif
}
expectedLabelSize.width = ceilf(expectedLabelSize.width);
expectedLabelSize.height = self.bounds.size.height;
return expectedLabelSize;
}
- (CGSize)sizeThatFits:(CGSize)size {
CGSize fitSize = [self.subLabel sizeThatFits:size];
fitSize.width += 2.0f * self.fadeLength;
return fitSize;
}
#pragma mark - Animation Handlers
- (BOOL)labelShouldScroll {
BOOL stringLength = ([self.subLabel.text length] > 0);
if (!stringLength) {
return NO;
}
BOOL labelWidth = (self.bounds.size.width < [self subLabelSize].width + (self.marqueeType == MLContinuous ? 2 * self.fadeLength : self.fadeLength));
return (!self.labelize && labelWidth);
}
- (NSTimeInterval)durationForInterval:(NSTimeInterval)interval {
switch (self.marqueeType) {
case MLContinuous:
return (interval * 2.0);
break;
default:
return interval;
break;
}
}
- (void)beginScroll {
[self beginScrollWithDelay:YES];
}
- (void)beginScrollWithDelay:(BOOL)delay {
switch (self.marqueeType) {
case MLContinuous:
case MLContinuousReverse:
[self scrollContinuousWithInterval:[self durationForInterval:self.animationDuration] after:(delay ? self.animationDelay : 0.0)];
break;
default:
[self scrollAwayWithInterval:[self durationForInterval:self.animationDuration]];
break;
}
}
- (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 {
if (![self superview]) {
return;
}
UIViewController *viewController = [self firstAvailableViewController];
if (!(viewController.isViewLoaded && viewController.view.window)) {
return;
}
// Perform animation
self.awayFromHome = YES;
[self.subLabel.layer removeAllAnimations];
[self.layer removeAllAnimations];
[UIView animateWithDuration:interval
delay:delayAmount
options:self.animationCurve
animations:^{
self.subLabel.frame = self.awayLabelFrame;
}
completion:^(BOOL finished) {
if (finished) {
[self scrollHomeWithInterval:interval delayAmount:delayAmount];
}
}];
}
- (void)scrollHomeWithInterval:(NSTimeInterval)interval {
[self scrollHomeWithInterval:interval delay:YES];
}
- (void)scrollHomeWithInterval:(NSTimeInterval)interval delay:(BOOL)delay {
[self scrollHomeWithInterval:interval delayAmount:(delay ? self.animationDelay : 0.0)];
}
- (void)scrollHomeWithInterval:(NSTimeInterval)interval delayAmount:(NSTimeInterval)delayAmount {
if (![self superview]) {
return;
}
[UIView animateWithDuration:interval
delay:delayAmount
options:self.animationCurve
animations:^{
self.subLabel.frame = self.homeLabelFrame;
}
completion:^(BOOL finished){
if (finished) {
// Set awayFromHome
self.awayFromHome = NO;
if (!self.tapToScroll && !self.holdScrolling) {
[self scrollAwayWithInterval:interval];
}
}
}];
}
- (void)scrollContinuousWithInterval:(NSTimeInterval)interval after:(NSTimeInterval)delayAmount {
if (![self superview]) {
return;
}
// Return labels to home frame
[self returnLabelToOriginImmediately];
UIViewController *viewController = [self firstAvailableViewController];
if (!(viewController.isViewLoaded && viewController.view.window)) {
return;
}
NSArray *labels = [self allSubLabels];
__block CGFloat offset = 0.0f;
self.awayFromHome = YES;
// Animate
[UIView animateWithDuration:interval
delay:delayAmount
options:self.animationCurve
animations:^{
for (UILabel *sl in labels) {
sl.frame = CGRectIntegral(CGRectOffset(self.awayLabelFrame, offset, 0.0f));
// Increment offset
offset += (self.marqueeType == MLContinuousReverse ? -1.0f : 1.0f) * (self.homeLabelFrame.size.width + 2 * self.fadeLength + self.continuousMarqueeExtraBuffer);
}
}
completion:^(BOOL finished) {
if (finished && !self.tapToScroll && !self.holdScrolling) {
self.awayFromHome = NO;
[self scrollContinuousWithInterval:interval after:delayAmount];
}
}];
}
- (void)returnLabelToOriginImmediately {
NSArray *labels = [self allSubLabels];
CGFloat offset = 0.0f;
for (UILabel *sl in labels) {
[sl.layer removeAllAnimations];
sl.frame = CGRectIntegral(CGRectOffset(self.homeLabelFrame, offset, 0.0f));
offset += (self.marqueeType == MLContinuousReverse ? -1.0f : 1.0f) * (self.homeLabelFrame.size.width + self.fadeLength + self.continuousMarqueeExtraBuffer);
}
if (self.subLabel.frame.origin.x == self.homeLabelFrame.origin.x) {
self.awayFromHome = NO;
}
}
#pragma mark - Label Control
- (void)restartLabel {
[self returnLabelToOriginImmediately];
if (self.labelShouldScroll && !self.tapToScroll) {
[self beginScroll];
}
}
- (void)resetLabel {
[self returnLabelToOriginImmediately];
self.homeLabelFrame = CGRectNull;
self.awayLabelFrame = CGRectNull;
}
- (void)shutdownLabel {
[self returnLabelToOriginImmediately];
}
-(void)pauseLabel
{
if (!self.isPaused) {
NSArray *labels = [self allSubLabels];
for (UILabel *sl in labels) {
CFTimeInterval pausedTime = [sl.layer convertTime:CACurrentMediaTime() fromLayer:nil];
sl.layer.speed = 0.0;
sl.layer.timeOffset = pausedTime;
}
self.isPaused = YES;
}
}
-(void)unpauseLabel
{
if (self.isPaused) {
NSArray *labels = [self allSubLabels];
for (UILabel *sl in labels) {
CFTimeInterval pausedTime = [sl.layer timeOffset];
sl.layer.speed = 1.0;
sl.layer.timeOffset = 0.0;
sl.layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [sl.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
sl.layer.beginTime = timeSincePause;
}
self.isPaused = NO;
}
}
- (void)labelWasTapped:(UITapGestureRecognizer *)recognizer {
if (self.labelShouldScroll) {
[self beginScrollWithDelay:NO];
}
}
#pragma mark - Modified UILabel Getters/Setters
- (void)setBounds:(CGRect)bounds {
CGRect oldBounds = self.bounds;
[super setBounds:bounds];
if (CGSizeEqualToSize(bounds.size, oldBounds.size)) {
return;
}
[self applyGradientMaskForFadeLength:self.fadeLength animated:!self.orientationWillChange];
[self updateSublabelAndLocationsAndBeginScroll:!self.orientationWillChange];
}
- (void)setFrame:(CGRect)frame {
CGRect oldFrame = self.frame;
[super setFrame:frame];
if (CGSizeEqualToSize(frame.size, oldFrame.size)) {
return;
}
[self applyGradientMaskForFadeLength:self.fadeLength animated:!self.orientationWillChange];
[self updateSublabelAndLocationsAndBeginScroll:!self.orientationWillChange];
}
- (NSString *)text {
return self.subLabel.text;
}
- (void)setText:(NSString *)text {
if ([text isEqualToString:self.subLabel.text]) {
return;
}
self.subLabel.text = text;
[self updateSublabelAndLocations];
}
- (UIFont *)font {
return self.subLabel.font;
}
- (void)setFont:(UIFont *)font {
if ([font isEqual:self.subLabel.font]) {
return;
}
self.subLabel.font = font;
[self updateSublabelAndLocations];
}
- (UIColor *)textColor {
return self.subLabel.textColor;
}
- (void)setTextColor:(UIColor *)textColor {
[self updateSubLabelsForKey:@"textColor" withValue:textColor];
}
- (UIColor *)backgroundColor {
return self.subLabel.backgroundColor;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
[self updateSubLabelsForKey:@"backgroundColor" withValue:backgroundColor];
}
- (UIColor *)shadowColor {
return self.subLabel.shadowColor;
}
- (void)setShadowColor:(UIColor *)shadowColor {
[self updateSubLabelsForKey:@"shadowColor" withValue:shadowColor];
}
- (CGSize)shadowOffset {
return self.subLabel.shadowOffset;
}
- (void)setShadowOffset:(CGSize)shadowOffset {
[self updateSubLabelsForKey:@"shadowOffset" withValue:[NSValue valueWithCGSize:shadowOffset]];
}
- (UIColor *)highlightedTextColor {
return self.subLabel.highlightedTextColor;
}
- (void)setHighlightedTextColor:(UIColor *)highlightedTextColor {
[self updateSubLabelsForKey:@"highlightedTextColor" withValue:highlightedTextColor];
}
- (BOOL)isHighlighted {
return self.subLabel.isHighlighted;
}
- (void)setHighlighted:(BOOL)highlighted {
[self updateSubLabelsForKey:@"highlighted" withValue:@(highlighted)];
}
- (BOOL)isEnabled {
return self.subLabel.isEnabled;
}
- (void)setEnabled:(BOOL)enabled {
[self updateSubLabelsForKey:@"enabled" withValue:@(enabled)];
}
- (void)setNumberOfLines:(NSInteger)numberOfLines {
// By the nature of MarqueeLabel, this is 1
[super setNumberOfLines:1];
}
- (void)setAdjustsFontSizeToFitWidth:(BOOL)adjustsFontSizeToFitWidth {
// By the nature of MarqueeLabel, this is NO
[super setAdjustsFontSizeToFitWidth:NO];
}
- (void)setMinimumFontSize:(CGFloat)minimumFontSize {
[super setMinimumFontSize:0.0];
}
- (UIBaselineAdjustment)baselineAdjustment {
return self.subLabel.baselineAdjustment;
}
- (void)setBaselineAdjustment:(UIBaselineAdjustment)baselineAdjustment {
[self updateSubLabelsForKey:@"baselineAdjustment" withValue:@(baselineAdjustment)];
}
- (CGSize)intrinsicContentSize {
return self.subLabel.intrinsicContentSize;
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000
- (NSAttributedString *)attributedText {
return self.subLabel.attributedText;
}
- (void)setAttributedText:(NSAttributedString *)attributedText {
if ([attributedText isEqualToAttributedString:self.subLabel.attributedText]) {
return;
}
self.subLabel.attributedText = attributedText;
[self updateSublabelAndLocations];
}
- (void)setAdjustsLetterSpacingToFitWidth:(BOOL)adjustsLetterSpacingToFitWidth {
// By the nature of MarqueeLabel, this is NO
[super setAdjustsLetterSpacingToFitWidth:NO];
}
- (void)setMinimumScaleFactor:(CGFloat)minimumScaleFactor {
[super setMinimumScaleFactor:0.0f];
}
#endif
- (void)refreshSubLabels:(NSArray *)subLabels {
for (UILabel *sl in subLabels) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000
sl.attributedText = self.attributedText;
#else
sl.text = self.text;
sl.font = self.font;
sl.textColor = self.textColor;
#endif
sl.backgroundColor = self.backgroundColor;
sl.shadowColor = self.shadowColor;
sl.shadowOffset = self.shadowOffset;
sl.textAlignment = NSTextAlignmentLeft;
}
}
- (void)updateSubLabelsForKey:(NSString *)key withValue:(id)value {
NSArray *labels = [self allSubLabels];
for (UILabel *sl in labels) {
[sl setValue:value forKeyPath:key];
}
}
- (void)updateSubLabelsForKeysWithValues:(NSDictionary *)dictionary {
NSArray *labels = [self allSubLabels];
for (UILabel *sl in labels) {
for (NSString *key in dictionary) {
[sl setValue:[dictionary objectForKey:key] forKey:key];
}
}
}
#pragma mark - Custom Getters and Setters
- (void)setRate:(CGFloat)rate {
if (_rate == rate) {
return;
}
_lengthOfScroll = 0.0f;
_rate = rate;
[self updateSublabelAndLocations];
}
- (void)setLengthOfScroll:(NSTimeInterval)lengthOfScroll {
if (_lengthOfScroll == lengthOfScroll) {
return;
}
_rate = 0.0f;
_lengthOfScroll = lengthOfScroll;
[self updateSublabelAndLocations];
}
- (void)setAnimationCurve:(UIViewAnimationOptions)animationCurve {
if (_animationCurve == animationCurve) {
return;
}
NSUInteger allowableOptions = UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionCurveLinear;
if ((allowableOptions & animationCurve) == animationCurve) {
_animationCurve = animationCurve;
}
}
- (void)setContinuousMarqueeExtraBuffer:(CGFloat)continuousMarqueeExtraBuffer {
if (_continuousMarqueeExtraBuffer == continuousMarqueeExtraBuffer) {
return;
}
// Do not allow negative values
_continuousMarqueeExtraBuffer = fabsf(continuousMarqueeExtraBuffer);
[self updateSublabelAndLocations];
}
- (void)setFadeLength:(CGFloat)fadeLength {
if (_fadeLength == fadeLength) {
return;
}
_fadeLength = fadeLength;
[self applyGradientMaskForFadeLength:_fadeLength];
[self updateSublabelAndLocations];
}
- (void)setTapToScroll:(BOOL)tapToScroll {
if (_tapToScroll == tapToScroll) {
return;
}
_tapToScroll = tapToScroll;
if (_tapToScroll) {
UITapGestureRecognizer *newTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelWasTapped:)];
[self addGestureRecognizer:newTapRecognizer];
self.tapRecognizer = newTapRecognizer;
self.userInteractionEnabled = YES;
} else {
[self removeGestureRecognizer:self.tapRecognizer];
self.tapRecognizer = nil;
self.userInteractionEnabled = NO;
}
}
- (void)setMarqueeType:(MarqueeType)marqueeType {
if (marqueeType == _marqueeType) {
return;
}
_marqueeType = marqueeType;
if (_marqueeType == MLContinuous) {
} else {
// Remove any second text layers
NSArray *labels = [self allSubLabels];
for (UILabel *sl in labels) {
if (sl != self.subLabel) {
[sl removeFromSuperview];
}
}
}
[self updateSublabelAndLocations];
}
- (CGRect)awayLabelFrame {
if (CGRectEqualToRect(_awayLabelFrame, CGRectNull)) {
// Calculate label size
CGSize expectedLabelSize = [self subLabelSize];