-
Notifications
You must be signed in to change notification settings - Fork 23
/
SDSegmentedControl.m
executable file
·1230 lines (1056 loc) · 36.6 KB
/
SDSegmentedControl.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
//
// SDSegmentedControl.m
// Created by Olivier Poitrey on 22/09/12.
// Contributed by Marius Rackwitz on 19/10/12
//
#import "SDSegmentedControl.h"
#import <QuartzCore/QuartzCore.h>
#pragma mark - Constants
const NSTimeInterval kSDSegmentedControlDefaultDuration = 0.2;
const CGFloat kSDSegmentedControlArrowSize = 6.5;
const CGFloat kSDSegmentedControlInterItemSpace = 30.0;
const UIEdgeInsets kSDSegmentedControlStainEdgeInsets = {-2, -16, -4, -16};
const CGSize kSDSegmentedControlImageSize = {18, 18};
const CGFloat kSDSegmentedControlScrollOffset = 20;
@interface SDSegmentView (Private)
- (CGRect)innerFrame;
@end
@interface SDSegmentedControl ()
@property (strong, nonatomic) NSMutableArray *_items;
@property (strong, nonatomic) UIView *_selectedStainView;
@end
@implementation SDSegmentedControl
{
NSInteger _selectedSegmentIndex;
NSInteger _lastSelectedSegmentIndex;
CAShapeLayer *_borderBottomLayer;
BOOL _isScrollingBySelection;
void (^lastCompletionBlock)();
}
+ (Class)layerClass
{
return CAShapeLayer.class;
}
- (id)init
{
if ((self = [super init]))
{
[self commonInit];
}
return self;
}
- (id)initWithItems:(NSArray *)items
{
if ((self = [self init]))
{
[items enumerateObjectsUsingBlock:^(id title, NSUInteger idx, BOOL *stop)
{
[self insertSegmentWithTitle:title atIndex:idx animated:NO];
}];
}
return self;
}
- (void)awakeFromNib
{
[self commonInit];
_selectedSegmentIndex = super.selectedSegmentIndex;
for (NSInteger i = 0; i < super.numberOfSegments; i++)
{
[self insertSegmentWithTitle:[super titleForSegmentAtIndex:i] atIndex:i animated:NO];
}
[super removeAllSegments];
}
- (void)commonInit
{
// Default height
CGRect frame = self.frame;
frame.size.height = 43;
self.frame = frame;
// Init properties
_lastSelectedSegmentIndex = UISegmentedControlNoSegment;
_selectedSegmentIndex = UISegmentedControlNoSegment;
_arrowHeightFactor = -1.0;
_interItemSpace = kSDSegmentedControlInterItemSpace;
_stainEdgeInsets = kSDSegmentedControlStainEdgeInsets;
__items = NSMutableArray.new;
// Appearance properties
_animationDuration = kSDSegmentedControlDefaultDuration;
_arrowSize = kSDSegmentedControlArrowSize;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// Reset UIKit original widget
[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
// Init layer
self.layer.backgroundColor = UIColor.clearColor.CGColor;
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)
{
self.backgroundColor = [UIColor colorWithRed:0.961 green:0.961 blue:0.961 alpha:1];
self.shadowColor = UIColor.blackColor;
self.shadowRadius = .8;
self.shadowOpacity = .6;
self.shadowOffset = CGSizeMake(0, 1);
}
else
{
self.backgroundColor = [UIColor clearColor];
}
// Init border bottom layer
[self.layer addSublayer:_borderBottomLayer = CAShapeLayer.layer];
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)
{
self.borderColor = UIColor.whiteColor;
self.borderWidth = .5;
}
else
{
self.borderColor = UIColor.blackColor;
self.borderWidth = .25;
}
_borderBottomLayer.fillColor = nil;
// Init scrollView
[self addSubview:_scrollView = UIScrollView.new];
_scrollView.delegate = self;
_scrollView.scrollsToTop = NO;
_scrollView.backgroundColor = UIColor.clearColor;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
// Init stain view
[_scrollView addSubview:self._selectedStainView = SDStainView.new];
}
- (UIColor *)backgroundColor
{
return [UIColor colorWithCGColor:((CAShapeLayer *)self.layer).fillColor];
}
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
((CAShapeLayer *)self.layer).fillColor = backgroundColor.CGColor;
}
- (UIColor *)shadowColor
{
return [UIColor colorWithCGColor:self.layer.shadowColor];
}
- (void)setShadowColor:(UIColor *)color
{
self.layer.shadowColor = color.CGColor;
}
- (CGFloat)shadowRadius
{
return self.layer.shadowRadius;
}
- (void)setShadowRadius:(CGFloat)shadowRadius
{
self.layer.shadowRadius = shadowRadius;
}
- (CGFloat)shadowOpacity
{
return self.layer.shadowOpacity;
}
- (void)setShadowOpacity:(CGFloat)shadowOpacity
{
self.layer.shadowOpacity = shadowOpacity;
}
- (CGSize)shadowOffset
{
return self.layer.shadowOffset;
}
- (void)setShadowOffset:(CGSize)shadowOffset
{
self.layer.shadowOffset = shadowOffset;
}
- (CGFloat)borderWidth
{
return _borderBottomLayer.lineWidth;
}
- (void)setBorderWidth:(CGFloat)borderWidth
{
_borderBottomLayer.lineWidth = borderWidth;
}
- (UIColor *)borderColor
{
return [UIColor colorWithCGColor:_borderBottomLayer.strokeColor];
}
- (void)setBorderColor:(UIColor *)borderColor
{
_borderBottomLayer.strokeColor = borderColor.CGColor;
}
#pragma mark - UIKit API
- (void)insertSegmentWithImage:(UIImage *)image atIndex:(NSUInteger)index animated:(BOOL)animated
{
[self insertSegmentWithTitle:nil image:image atIndex:index animated:animated];
}
- (UIImage *)imageForSegmentAtIndex:(NSUInteger)index
{
return [[self segmentAtIndex:index] imageForState:UIControlStateNormal];
}
- (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)index
{
SDSegmentView* segmentView = [self segmentAtIndex:index];
[segmentView setImage:image forState:UIControlStateNormal];
[segmentView sizeToFit];
[self setNeedsLayout];
}
- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)index
{
index = MAX(MIN(index, self.numberOfSegments - 1), 0);
UIButton *segmentView = self._items[index];
[segmentView setTitle:title forState:UIControlStateNormal];
[segmentView sizeToFit];
[self setNeedsLayout];
}
- (NSString *)titleForSegmentAtIndex:(NSUInteger)index
{
index = MAX(MIN(index, self.numberOfSegments - 1), 0);
UIButton *segmentView = self._items[index];
return [segmentView titleForState:UIControlStateNormal];
}
- (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)index animated:(BOOL)animated
{
[self insertSegmentWithTitle:title image:nil atIndex:index animated:animated];
}
- (void)removeSegmentAtIndex:(NSUInteger)index animated:(BOOL)animated
{
if (self._items.count == 0) return;
index = MAX(MIN(index, self.numberOfSegments - 1), 0);
UIView *segmentView = self._items[index];
[self._items removeObject:segmentView];
if (self.selectedSegmentIndex >= 0)
{
BOOL changed = NO;
if (self._items.count == 1)
{
// Deselect if there is no item
self.selectedSegmentIndex = UISegmentedControlNoSegment;
changed = YES;
}
else if (self.selectedSegmentIndex == index)
{
// Inform that the old value doesn't exist anymore
changed = YES;
self.selectedSegmentIndex = [self firstEnabledSegmentIndexNearIndex:self.selectedSegmentIndex];
}
else if (self.selectedSegmentIndex > index)
{
self.selectedSegmentIndex = [self firstEnabledSegmentIndexNearIndex:self.selectedSegmentIndex - 1];
}
// It is important to set both, this will fix the animation.
_lastSelectedSegmentIndex = self.selectedSegmentIndex;
if (changed)
{
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
if (animated)
{
[UIView animateWithDuration:.4 animations:^
{
segmentView.alpha = 0;
[self layoutSegments];
}
completion:^(BOOL finished)
{
[segmentView removeFromSuperview];
}];
}
else
{
[segmentView removeFromSuperview];
[self setNeedsLayout];
}
}
- (void)removeAllSegments
{
[self._items makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self._items removeAllObjects];
self.selectedSegmentIndex = UISegmentedControlNoSegment;
[self setNeedsLayout];
}
- (NSUInteger)numberOfSegments
{
return self._items.count;
}
- (void)setEnabled:(BOOL)enabled forSegmentAtIndex:(NSUInteger)index
{
[self segmentAtIndex:index].enabled = enabled;
if (index == self.selectedSegmentIndex)
{
self.selectedSegmentIndex = [self firstEnabledSegmentIndexNearIndex:index];
}
}
- (BOOL)isEnabledForSegmentAtIndex:(NSUInteger)index
{
return [self segmentAtIndex:index].enabled;
}
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex
{
if (_selectedSegmentIndex != selectedSegmentIndex)
{
if (selectedSegmentIndex >= (NSInteger)self._items.count)
{
selectedSegmentIndex = self._items.count - 1;
}
_lastSelectedSegmentIndex = _selectedSegmentIndex;
_selectedSegmentIndex = selectedSegmentIndex;
[self setNeedsLayout];
}
}
- (NSInteger)selectedSegmentIndex
{
return _selectedSegmentIndex;
}
- (void)setWidth:(CGFloat)width forSegmentAtIndex:(NSUInteger)index
{
SDSegmentView *segmentView = [self segmentAtIndex:index];
CGRect frame = segmentView.frame;
frame.size.width = width;
segmentView.frame = frame;
[self setNeedsLayout];
}
- (CGFloat)widthForSegmentAtIndex:(NSUInteger)index
{
return CGRectGetWidth([self segmentAtIndex:index].frame);
}
# pragma mark - Private
- (void)insertSegmentWithTitle:(NSString *)title image:(UIImage *)image atIndex:(NSUInteger)index animated:(BOOL)animated
{
SDSegmentView *segmentView = SDSegmentView.new;
[segmentView addTarget:self action:@selector(handleSelect:) forControlEvents:UIControlEventTouchUpInside];
segmentView.alpha = 0;
[segmentView setTitle:title forState:UIControlStateNormal];
[segmentView setImage:image forState:UIControlStateNormal];
[segmentView sizeToFit];
index = MAX(MIN(index, self.numberOfSegments), 0);
if (index < self._items.count)
{
segmentView.center = ((UIView *)self._items[index]).center;
[self.scrollView insertSubview:segmentView belowSubview:self._items[index]];
[self._items insertObject:segmentView atIndex:index];
}
else
{
segmentView.center = self.center;
[self.scrollView addSubview:segmentView];
[self._items addObject:segmentView];
}
if (self.selectedSegmentIndex >= index && self.selectedSegmentIndex + 1 < self._items.count)
{
self.selectedSegmentIndex++;
}
_lastSelectedSegmentIndex = self.selectedSegmentIndex;
if (animated)
{
[UIView animateWithDuration:.4 animations:^
{
[self layoutSegments];
}];
}
else
{
[self setNeedsLayout];
}
}
- (NSInteger)firstEnabledSegmentIndexNearIndex:(NSUInteger)index
{
// Select the first enabled segment
for (int i = index; i < self._items.count; i++)
{
if (((SDSegmentView *)self._items[i]).enabled)
{
return i;
}
}
for (int i = index; i >= 0; i--)
{
if (((SDSegmentView *)self._items[i]).enabled)
{
return i;
}
}
return UISegmentedControlNoSegment;
}
- (SDSegmentView *)segmentAtIndex:(NSUInteger)index
{
NSParameterAssert(index >= 0 && index < self._items.count);
return self._items[index];
}
- (void)willMoveToSuperview:(UIView *)newSuperview
{
CGRect frame = self.frame;
if (frame.size.height == 0)
{
frame.size.height = 43;
}
if (frame.size.width == 0)
{
frame.size.width = CGRectGetWidth(newSuperview.bounds);
}
}
- (void)setArrowSize:(CGFloat)arrowSize
{
_arrowSize = arrowSize;
[self setNeedsLayout];
}
- (void)setArrowHeightFactor:(CGFloat)arrowHeightFactor
{
_arrowHeightFactor = arrowHeightFactor;
[self setNeedsLayout];
}
- (void)layoutSubviews
{
self.scrollView.frame = self.bounds;
[self layoutSegments];
}
- (void)layoutSegments
{
CGFloat totalItemWidth = 0;
for (SDSegmentView *item in self._items)
{
totalItemWidth += CGRectGetWidth(item.bounds);
}
CGFloat totalWidth = (totalItemWidth + (self.interItemSpace * (self.numberOfSegments - 1)));
// Apply total to scrollView
__block CGFloat currentItemPosition = 0;
CGSize contentSize = self.scrollView.contentSize;
if (totalWidth > self.bounds.size.width)
{
// We must scroll, so add an offset
totalWidth += 2 * kSDSegmentedControlScrollOffset;
currentItemPosition += kSDSegmentedControlScrollOffset;
contentSize.width = totalWidth;
}
else
{
contentSize.width = CGRectGetWidth(self.bounds);
}
contentSize.height = self.bounds.size.height;
self.scrollView.contentSize = contentSize;
// Center all items horizontally and each item vertically
CGFloat spaceLeft = self.scrollView.contentSize.width - totalWidth;
CGFloat itemHeight = self.scrollView.contentSize.height - self.arrowSize / 2 + .5;
currentItemPosition += spaceLeft / 2;
[self._items enumerateObjectsUsingBlock:^(SDSegmentView *item, NSUInteger idx, BOOL *stop)
{
item.alpha = 1;
item.frame = CGRectIntegral(CGRectMake(currentItemPosition, 0, CGRectGetWidth(item.bounds), itemHeight));
currentItemPosition = CGRectGetMaxX(item.frame) + self.interItemSpace;
}];
// Layout stain view and update items
BOOL animated = self.animationDuration && !CGRectEqualToRect(self._selectedStainView.frame, CGRectZero);
BOOL isScrollingSinceNow = NO;
CGFloat selectedItemCenterPosition;
if (self.selectedSegmentIndex == UISegmentedControlNoSegment)
{
self._selectedStainView.hidden = YES;
selectedItemCenterPosition = CGFLOAT_MAX;
for (SDSegmentView *item in self._items)
{
item.selected = NO;
}
}
else
{
SDSegmentView *selectedItem = self._items[self.selectedSegmentIndex];
selectedItemCenterPosition = selectedItem.center.x;
CGRect stainFrame = UIEdgeInsetsInsetRect(selectedItem.innerFrame, self.stainEdgeInsets);
self._selectedStainView.layer.cornerRadius = CGRectGetHeight(stainFrame) / 2;
self._selectedStainView.hidden = NO;
stainFrame.origin.x = roundf(selectedItemCenterPosition - CGRectGetWidth(stainFrame) / 2);
selectedItemCenterPosition -= self.scrollView.contentOffset.x;
if (self.scrollView.contentSize.width > self.scrollView.bounds.size.width)
{
CGRect scrollRect = {self.scrollView.contentOffset, self.scrollView.bounds.size};
CGRect targetRect = CGRectInset(stainFrame, -kSDSegmentedControlScrollOffset / 2, 0);
if (!CGRectContainsRect(scrollRect, targetRect))
{
// Adjust position
CGFloat posOffset = 0;
if (CGRectGetMinX(targetRect) < CGRectGetMinX(scrollRect))
{
posOffset += CGRectGetMinX(scrollRect) - CGRectGetMinX(targetRect);
}
else if (CGRectGetMaxX(targetRect) > CGRectGetMaxX(scrollRect))
{
posOffset -= CGRectGetMaxX(targetRect) - CGRectGetMaxX(scrollRect);
}
// Recenter arrow with posOffset
selectedItemCenterPosition += posOffset;
// Temporary disable updates, if scrolling is needed, because scrollView will cause a
// lot of relayouts. The field isScrollBySelection will be reseted by scrollView's delegate
// call to scrollViewDidEndScrollingAnimation and can't be resetted after called, because
// the animation is dispatched asynchronously, naturally.
_isScrollingBySelection = animated;
isScrollingSinceNow = YES;
[self.scrollView scrollRectToVisible:targetRect animated:animated];
}
}
UIView.animationsEnabled = animated;
[UIView animateWithDuration:animated ? self.animationDuration : 0 animations:^
{
self._selectedStainView.frame = stainFrame;
}
completion:^(BOOL finished)
{
for (SDSegmentView *item in self._items)
{
item.selected = item == selectedItem;
}
}];
UIView.animationsEnabled = YES;
}
// Don't relayout paths while scrolling
if (!_isScrollingBySelection || isScrollingSinceNow)
{
// Animate from a custom oldPosition if needed
CGFloat oldPosition = CGFLOAT_MAX;
if (animated && _lastSelectedSegmentIndex != self.selectedSegmentIndex && _lastSelectedSegmentIndex >= 0 && _lastSelectedSegmentIndex < self._items.count)
{
SDSegmentView *lastSegmentView = [self._items objectAtIndex:_lastSelectedSegmentIndex];
oldPosition = lastSegmentView.center.x - self.scrollView.contentOffset.x;
}
[self drawPathsFromPosition:oldPosition toPosition:selectedItemCenterPosition animationDuration:animated ? self.animationDuration : 0];
}
}
#pragma mark - Draw paths
// Actually paths are not drawn here, instead they are relayouted
- (void)drawPathsToPosition:(CGFloat)position animated:(BOOL)animated
{
[self drawPathsToPosition:position animationDuration:animated ? self.animationDuration : 0 completion:nil];
}
- (void)drawPathsToPosition:(CGFloat)position animationDuration:(CFTimeInterval)duration completion:(void (^)(void))completion
{
[self drawPathsFromPosition:CGFLOAT_MAX toPosition:position animationDuration:duration completion:completion];
}
- (void)drawPathsFromPosition:(CGFloat)oldPosition toPosition:(CGFloat)position animationDuration:(CFTimeInterval)duration
{
[self drawPathsFromPosition:oldPosition toPosition:position animationDuration:duration completion:nil];
}
- (void)drawPathsFromPosition:(CGFloat)oldPosition toPosition:(CGFloat)position animationDuration:(CFTimeInterval)duration completion:(void (^)(void))completion
{
CGRect bounds = self.bounds;
CGFloat left = CGRectGetMinX(bounds);
CGFloat right = CGRectGetMaxX(bounds);
CGFloat top = CGRectGetMinY(bounds);
CGFloat bottom = CGRectGetMaxY(bounds);
//
// Mask
//
__block UIBezierPath *path = UIBezierPath.new;
[path moveToPoint:bounds.origin];
[self addArrowAtPoint:CGPointMake(position, bottom) toPath:path withLineWidth:0.0];
[path addLineToPoint:CGPointMake(right, top)];
[path addLineToPoint:CGPointMake(left, top)];
//
// Shadow mask
//
top += 10;
__block UIBezierPath *shadowPath = UIBezierPath.new;
[shadowPath moveToPoint:CGPointMake(left, top)];
[self addArrowAtPoint:CGPointMake(position, bottom) toPath:shadowPath withLineWidth:0.0];
[shadowPath addLineToPoint:CGPointMake(right, top)];
[shadowPath addLineToPoint:CGPointMake(left, top)];
//
// Bottom white line
//
_borderBottomLayer.frame = self.bounds;
__block UIBezierPath *borderBottomPath = UIBezierPath.new;
const CGFloat lineY = bottom - _borderBottomLayer.lineWidth;
[self addArrowAtPoint:CGPointMake(position, lineY) toPath:borderBottomPath withLineWidth:_borderBottomLayer.lineWidth];
// Skip current animations and ensure the completion block was applied
// otherwise this will end up in ugly effects if the selection was changed very fast
[self.layer removeAllAnimations];
[_borderBottomLayer removeAllAnimations];
if (lastCompletionBlock)
{
lastCompletionBlock();
}
// Build block
void(^assignLayerPaths)() = ^
{
((CAShapeLayer *)self.layer).path = path.CGPath;
self.layer.shadowPath = shadowPath.CGPath;
_borderBottomLayer.path = borderBottomPath.CGPath;
// Dereference itself to be not executed twice
lastCompletionBlock = nil;
};
__block void(^animationCompletion)();
if (completion)
{
animationCompletion = ^
{
assignLayerPaths();
completion();
};
}
else
{
animationCompletion = assignLayerPaths;
}
// Apply new paths
if (duration > 0)
{
// That's a bit fragile: we detect stop animation call by duration!
NSString *timingFuncName = duration < self.animationDuration ? kCAMediaTimingFunctionEaseIn : kCAMediaTimingFunctionEaseInEaseOut;
// Check if we have to do a stop animation, which means that we first
// animate to have a fully visible arrow and then move the arrow.
// Otherwise there will be ugly effects.
CFTimeInterval stopDuration = -1;
CGFloat stopPosition = -1;
if (oldPosition < CGFLOAT_MAX)
{
if (oldPosition < left+self.arrowSize)
{
stopPosition = left+self.arrowSize;
}
else if (oldPosition > right-self.arrowSize)
{
stopPosition = right-self.arrowSize;
}
if (stopPosition > 0)
{
float relStopDuration = ABS((stopPosition - oldPosition) / (position - oldPosition));
if (relStopDuration > 1)
{
relStopDuration = 1.0 / relStopDuration;
}
stopDuration = duration * relStopDuration;
duration -= stopDuration;
timingFuncName = kCAMediaTimingFunctionEaseOut;
}
}
void (^animation)() = ^
{
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
CAMediaTimingFunction *timing = [CAMediaTimingFunction functionWithName:timingFuncName];
[CATransaction setAnimationTimingFunction:timing];
[CATransaction setCompletionBlock:animationCompletion];
[self addAnimationWithDuration:duration onLayer:self.layer forKey:@"path" toPath:path];
[self addAnimationWithDuration:duration onLayer:self.layer forKey:@"shadow" toPath:shadowPath];
[self addAnimationWithDuration:duration onLayer:_borderBottomLayer forKey:@"path" toPath:borderBottomPath];
[CATransaction commit];
};
if (stopPosition > 0)
{
[self drawPathsToPosition:stopPosition animationDuration:stopDuration completion:animation];
}
else
{
animation();
}
// Remember completion block
lastCompletionBlock = assignLayerPaths;
}
else
{
assignLayerPaths();
}
}
- (void)addAnimationWithDuration:(CFTimeInterval)duration onLayer:(CALayer *)layer forKey:(NSString *)key toPath:(UIBezierPath *)path
{
NSString *camelCaseKeyPath;
NSString *keyPath;
if ([key isEqual:@"path"])
{
camelCaseKeyPath = key;
keyPath = key;
}
else
{
camelCaseKeyPath = [NSString stringWithFormat:@"%@Path", key];
keyPath = [NSString stringWithFormat:@"%@.path", key];
}
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:camelCaseKeyPath];
pathAnimation.removedOnCompletion = NO;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.duration = duration;
pathAnimation.fromValue = [layer valueForKey:keyPath];
pathAnimation.toValue = (id)path.CGPath;
[layer addAnimation:pathAnimation forKey:key];
}
- (void)addArrowAtPoint:(CGPoint)point toPath:(UIBezierPath *)path withLineWidth:(CGFloat)lineWidth
{
// The arrow is added like below, whereas P is the point argument
// and 1-5 are the points which were added to the path. It must be
// always five points, otherwise animations will look ugly.
//
// P: point.x
// s: self.arrowSize - line.width
// w: self.bounds.size.width
//
//
// s < P < w-s: P < -s: P = MAX: w+s < P:
//
// 3
// / \
// / \
// 1--2 P 4--5 1234--------5 1--2--3--4--5 1--------2345
//
//
// 0 < P < s: -s < P:
//
// 3
// / \ 123
// 12 \ \
// P 4-----5 P 4------5
//
const CGFloat left = CGRectGetMinX(self.bounds);
const CGFloat right = CGRectGetMaxX(self.bounds);
const CGFloat center = (right-left) / 2;
const CGFloat width = self.arrowSize - lineWidth;
const CGFloat height = self.arrowSize + lineWidth/2;
const CGFloat ratio = self.arrowHeightFactor;
__block NSMutableArray *points = NSMutableArray.new;
BOOL hasCustomLastPoint = NO;
void (^addPoint)(CGFloat x, CGFloat y) = ^(CGFloat x, CGFloat y)
{
[points addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
};
// Add first point
addPoint(left, point.y);
if (_arrowSize <= 0.02)
{
addPoint(point.x - lineWidth, point.y);
addPoint(point.x, point.y);
addPoint(point.x + lineWidth, point.y);
}
else if (point.x >= left+width && point.x <= right-width)
{
// Arrow is completely inside the view
addPoint(point.x - width, point.y);
addPoint(point.x, point.y + ratio * height);
addPoint(point.x + width, point.y);
}
else
{
// Just some tricks, to allow correctly cutted arrows and
// to have always a proper animation.
if (point.x <= left-width)
{
// Left aligned points
addPoint(left + 0.01, point.y);
addPoint(left + 0.02, point.y);
addPoint(left + 0.03, point.y);
}
else if (point.x < left+width && point.x > left-width)
{
// Left cutted arrow
[points removeAllObjects]; // Custom first point
if (point.x < left)
{
CGFloat x = width + point.x;
addPoint(left, point.y + ratio * x);
addPoint(left + 0.01, point.y + ratio * (x + 0.01));
addPoint(left + 0.02, point.y + ratio * (x + 0.02));
addPoint(left + x, point.y);
}
else
{
CGFloat x = width - point.x;
addPoint(left, point.y + ratio * x);
addPoint(left + 0.01, point.y + ratio * (x + 0.01));
addPoint(point.x, point.y + ratio * height);
addPoint(point.x + width, point.y);
}
}
else if (point.x == CGFLOAT_MAX)
{
// Centered "arrow", with zero height
addPoint(center - width, point.y);
addPoint(center, point.y);
addPoint(center + width, point.y);
}
else if (point.x < right+width && point.x > right-width)
{
// Right cutted arrow, is like left cutted arrow but:
// * swapped if/else case
// * inverse point order
// * other calculation of x
hasCustomLastPoint = YES; // Custom last point
if (point.x < right)
{
CGFloat x = width - (right - point.x);
addPoint(point.x - width, point.y);
addPoint(point.x, point.y + ratio * height);
addPoint(right - 0.01, point.y + ratio * (x + 0.01));
addPoint(right, point.y + ratio * x);
}
else
{
CGFloat x = width + (right - point.x);
addPoint(right - x, point.y);
addPoint(right - 0.02, point.y + ratio * (x + 0.02));
addPoint(right - 0.01, point.y + ratio * (x + 0.01));
addPoint(right, point.y + ratio * x);
}
}
else
{
// Right aligned points
addPoint(right - 0.03, point.y);
addPoint(right - 0.02, point.y);
addPoint(right - 0.01, point.y);
}
}
// Add points from array to path
CGPoint node = ((NSValue *)[points objectAtIndex:0]).CGPointValue;
if (path.isEmpty)
{
[path moveToPoint:node];
}
else
{
[path addLineToPoint:node];
}
for (int i=1; i<points.count; i++)
{
node = ((NSValue *)[points objectAtIndex:i]).CGPointValue;
[path addLineToPoint:node];
}
// Add last point of not replaced
if (!hasCustomLastPoint)
{
[path addLineToPoint:CGPointMake(right, point.y)];
}
}
- (void)handleSelect:(SDSegmentView *)view
{
NSUInteger index = [self._items indexOfObject:view];
if (index != NSNotFound && index != self.selectedSegmentIndex)
{
self.selectedSegmentIndex = index;
[self setNeedsLayout];
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (_isScrollingBySelection || _selectedSegmentIndex == UISegmentedControlNoSegment) return;
CGFloat selectedItemCenterPosition = ((SDSegmentView *)self._items[self.selectedSegmentIndex]).center.x;
[self drawPathsToPosition:selectedItemCenterPosition - scrollView.contentOffset.x animated:NO];
self._selectedStainView.center = CGPointMake(selectedItemCenterPosition, self._selectedStainView.center.y);
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
_isScrollingBySelection = NO;
}
@end
@implementation SDSegmentView
+ (void)initialize
{
[super initialize];
SDSegmentView *appearance = [self appearance];
[appearance setTitleColor:[UIColor colorWithWhite:0.392 alpha:1] forState:UIControlStateNormal];
[appearance setTitleColor:[UIColor colorWithWhite:0.235 alpha:1] forState:UIControlStateSelected];
[appearance setTitleColor:[UIColor colorWithWhite:0.800 alpha:1] forState:UIControlStateDisabled];
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)
{
[appearance setTitleShadowColor:UIColor.whiteColor forState:UIControlStateNormal];
[appearance setTitleShadowColor:UIColor.whiteColor forState:UIControlStateSelected];
[appearance setTitleShadowColor:UIColor.clearColor forState:UIControlStateDisabled];
}
}
+ (SDSegmentView *)new
{
return [self.class buttonWithType:UIButtonTypeCustom];
}
+ (id)appearance
{
return [self appearanceWhenContainedIn:SDSegmentedControl.class, nil];
}
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
_imageSize = kSDSegmentedControlImageSize;