-
Notifications
You must be signed in to change notification settings - Fork 189
/
SMCalloutView.m
executable file
·859 lines (685 loc) · 38.4 KB
/
SMCalloutView.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
#import "SMCalloutView.h"
//
// UIView frame helpers - we do a lot of UIView frame fiddling in this class; these functions help keep things readable.
//
@interface UIView (SMFrameAdditions)
@property (nonatomic, assign) CGPoint frameOrigin;
@property (nonatomic, assign) CGSize frameSize;
@property (nonatomic, assign) CGFloat frameX, frameY, frameWidth, frameHeight; // normal rect properties
@property (nonatomic, assign) CGFloat frameLeft, frameTop, frameRight, frameBottom; // these will stretch/shrink the rect
@end
//
// Callout View.
//
#define CALLOUT_DEFAULT_CONTAINER_HEIGHT 44 // height of just the main portion without arrow
#define CALLOUT_SUB_DEFAULT_CONTAINER_HEIGHT 52 // height of just the main portion without arrow (when subtitle is present)
#define CALLOUT_MIN_WIDTH 61 // minimum width of system callout
#define TITLE_HMARGIN 12 // the title/subtitle view's normal horizontal margin from the edges of our callout view or from the accessories
#define TITLE_TOP 11 // the top of the title view when no subtitle is present
#define TITLE_SUB_TOP 4 // the top of the title view when a subtitle IS present
#define TITLE_HEIGHT 21 // title height, fixed
#define SUBTITLE_TOP 28 // the top of the subtitle, when present
#define SUBTITLE_HEIGHT 15 // subtitle height, fixed
#define BETWEEN_ACCESSORIES_MARGIN 7 // margin between accessories when no title/subtitle is present
#define TOP_ANCHOR_MARGIN 13 // all the above measurements assume a bottom anchor! if we're pointing "up" we'll need to add this top margin to everything.
#define COMFORTABLE_MARGIN 10 // when we try to reposition content to be visible, we'll consider this margin around your target rect
NSTimeInterval const kSMCalloutViewRepositionDelayForUIScrollView = 1.0/3.0;
@interface SMCalloutView ()
@property (nonatomic, strong) UIButton *containerView; // for masking and interaction
@property (nonatomic, strong) UILabel *titleLabel, *subtitleLabel;
@property (nonatomic, assign) SMCalloutArrowDirection currentArrowDirection;
@property (nonatomic, assign) BOOL popupCancelled;
@end
@implementation SMCalloutView
+ (SMCalloutView *)platformCalloutView {
// if you haven't compiled SMClassicCalloutView into your app, then we can't possibly create an instance of it!
if (!NSClassFromString(@"SMClassicCalloutView"))
return [SMCalloutView new];
// ok we have both - so choose the best one based on current platform
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
return [SMCalloutView new]; // iOS 7+
else
return [NSClassFromString(@"SMClassicCalloutView") new];
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.permittedArrowDirection = SMCalloutArrowDirectionDown;
self.presentAnimation = SMCalloutAnimationBounce;
self.dismissAnimation = SMCalloutAnimationFade;
self.backgroundColor = [UIColor clearColor];
self.containerView = [UIButton new];
self.containerView.isAccessibilityElement = NO;
self.isAccessibilityElement = NO;
self.contentViewInset = UIEdgeInsetsMake(12, 12, 12, 12);
[self.containerView addTarget:self action:@selector(highlightIfNecessary) forControlEvents:UIControlEventTouchDown | UIControlEventTouchDragInside];
[self.containerView addTarget:self action:@selector(unhighlightIfNecessary) forControlEvents:UIControlEventTouchDragOutside | UIControlEventTouchCancel | UIControlEventTouchUpOutside | UIControlEventTouchUpInside];
[self.containerView addTarget:self action:@selector(calloutClicked) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (BOOL)supportsHighlighting {
if (![self.delegate respondsToSelector:@selector(calloutViewClicked:)])
return NO;
if ([self.delegate respondsToSelector:@selector(calloutViewShouldHighlight:)])
return [self.delegate calloutViewShouldHighlight:self];
return YES;
}
- (void)highlightIfNecessary { if (self.supportsHighlighting) self.backgroundView.highlighted = YES; }
- (void)unhighlightIfNecessary { if (self.supportsHighlighting) self.backgroundView.highlighted = NO; }
- (void)calloutClicked {
if ([self.delegate respondsToSelector:@selector(calloutViewClicked:)])
[self.delegate calloutViewClicked:self];
}
- (UIView *)titleViewOrDefault {
if (self.titleView)
// if you have a custom title view defined, return that.
return self.titleView;
else {
if (!self.titleLabel) {
// create a default titleView
self.titleLabel = [UILabel new];
self.titleLabel.frameHeight = TITLE_HEIGHT;
self.titleLabel.opaque = NO;
self.titleLabel.backgroundColor = [UIColor clearColor];
self.titleLabel.font = [UIFont systemFontOfSize:17];
if (@available(iOS 13.0, *)) {
self.titleLabel.textColor = [UIColor labelColor];
} else {
self.titleLabel.textColor = [UIColor blackColor];
}
}
return self.titleLabel;
}
}
- (UIView *)subtitleViewOrDefault {
if (self.subtitleView)
// if you have a custom subtitle view defined, return that.
return self.subtitleView;
else {
if (!self.subtitleLabel) {
// create a default subtitleView
self.subtitleLabel = [UILabel new];
self.subtitleLabel.frameHeight = SUBTITLE_HEIGHT;
self.subtitleLabel.opaque = NO;
self.subtitleLabel.backgroundColor = [UIColor clearColor];
self.subtitleLabel.font = [UIFont systemFontOfSize:12];
if (@available(iOS 13.0, *)) {
self.subtitleLabel.textColor = [UIColor secondaryLabelColor];
} else {
self.subtitleLabel.textColor = [UIColor blackColor];
}
}
return self.subtitleLabel;
}
}
- (SMCalloutBackgroundView *)backgroundView {
// create our default background on first access only if it's nil, since you might have set your own background anyway.
return _backgroundView ? _backgroundView : (_backgroundView = [self defaultBackgroundView]);
}
- (SMCalloutBackgroundView *)defaultBackgroundView {
return [SMCalloutMaskedBackgroundView new];
}
- (void)rebuildSubviews {
// remove and re-add our appropriate subviews in the appropriate order
[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self setNeedsDisplay];
[self addSubview:self.backgroundView];
[self addSubview:self.containerView];
if (self.contentView) {
[self.containerView addSubview:self.contentView];
}
else {
if (self.titleViewOrDefault) [self.containerView addSubview:self.titleViewOrDefault];
if (self.subtitleViewOrDefault) [self.containerView addSubview:self.subtitleViewOrDefault];
}
if (self.leftAccessoryView) [self.containerView addSubview:self.leftAccessoryView];
if (self.rightAccessoryView) [self.containerView addSubview:self.rightAccessoryView];
}
// Accessory margins. Accessories are centered vertically when shorter
// than the callout, otherwise they grow from the upper corner.
- (CGFloat)leftAccessoryVerticalMargin {
if (self.leftAccessoryView.frameHeight < self.calloutContainerHeight)
return round((self.calloutContainerHeight - self.leftAccessoryView.frameHeight) / 2);
else
return 0;
}
- (CGFloat)leftAccessoryHorizontalMargin {
return fmin(self.leftAccessoryVerticalMargin, TITLE_HMARGIN);
}
- (CGFloat)rightAccessoryVerticalMargin {
if (self.rightAccessoryView.frameHeight < self.calloutContainerHeight)
return round((self.calloutContainerHeight - self.rightAccessoryView.frameHeight) / 2);
else
return 0;
}
- (CGFloat)rightAccessoryHorizontalMargin {
return fmin(self.rightAccessoryVerticalMargin, TITLE_HMARGIN);
}
- (CGFloat)innerContentMarginLeft {
if (self.leftAccessoryView)
return self.leftAccessoryHorizontalMargin + self.leftAccessoryView.frameWidth + TITLE_HMARGIN;
else
return self.contentViewInset.left;
}
- (CGFloat)innerContentMarginRight {
if (self.rightAccessoryView)
return self.rightAccessoryHorizontalMargin + self.rightAccessoryView.frameWidth + TITLE_HMARGIN;
else
return self.contentViewInset.right;
}
- (CGFloat)calloutHeight {
return self.calloutContainerHeight + self.backgroundView.anchorHeight;
}
- (CGFloat)calloutContainerHeight {
if (self.contentView)
return self.contentView.frameHeight + self.contentViewInset.bottom + self.contentViewInset.top;
else if (self.subtitleView || self.subtitle.length > 0)
return CALLOUT_SUB_DEFAULT_CONTAINER_HEIGHT;
else
return CALLOUT_DEFAULT_CONTAINER_HEIGHT;
}
- (CGSize)sizeThatFits:(CGSize)size {
// calculate how much non-negotiable space we need to reserve for margin and accessories
CGFloat margin = self.innerContentMarginLeft + self.innerContentMarginRight;
// how much room is left for text?
CGFloat availableWidthForText = size.width - margin - 1;
// no room for text? then we'll have to squeeze into the given size somehow.
if (availableWidthForText < 0)
availableWidthForText = 0;
CGSize preferredTitleSize = [self.titleViewOrDefault sizeThatFits:CGSizeMake(availableWidthForText, TITLE_HEIGHT)];
CGSize preferredSubtitleSize = [self.subtitleViewOrDefault sizeThatFits:CGSizeMake(availableWidthForText, SUBTITLE_HEIGHT)];
// total width we'd like
CGFloat preferredWidth;
if (self.contentView) {
// if we have a content view, then take our preferred size directly from that
preferredWidth = self.contentView.frameWidth + margin;
}
else if (preferredTitleSize.width >= 0.000001 || preferredSubtitleSize.width >= 0.000001) {
// if we have a title or subtitle, then our assumed margins are valid, and we can apply them
preferredWidth = fmax(preferredTitleSize.width, preferredSubtitleSize.width) + margin;
}
else {
// ok we have no title or subtitle to speak of. In this case, the system callout would actually not display
// at all! But we can handle it.
preferredWidth = self.leftAccessoryView.frameWidth + self.rightAccessoryView.frameWidth + self.leftAccessoryHorizontalMargin + self.rightAccessoryHorizontalMargin;
if (self.leftAccessoryView && self.rightAccessoryView)
preferredWidth += BETWEEN_ACCESSORIES_MARGIN;
}
// ensure we're big enough to fit our graphics!
preferredWidth = fmax(preferredWidth, CALLOUT_MIN_WIDTH);
// ask to be smaller if we have space, otherwise we'll fit into what we have by truncating the title/subtitle.
return CGSizeMake(fmin(preferredWidth, size.width), self.calloutHeight);
}
- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect {
CGFloat nudgeRight = fmax(0, CGRectGetMinX(outerRect) - CGRectGetMinX(innerRect));
CGFloat nudgeLeft = fmin(0, CGRectGetMaxX(outerRect) - CGRectGetMaxX(innerRect));
CGFloat nudgeTop = fmax(0, CGRectGetMinY(outerRect) - CGRectGetMinY(innerRect));
CGFloat nudgeBottom = fmin(0, CGRectGetMaxY(outerRect) - CGRectGetMaxY(innerRect));
return CGSizeMake(nudgeLeft > 0 ? nudgeLeft : nudgeRight, nudgeTop > 0 ? nudgeTop : nudgeBottom);
}
- (void)presentCalloutFromRect:(CGRect)rect inView:(UIView *)view constrainedToView:(UIView *)constrainedView animated:(BOOL)animated {
[self presentCalloutFromRect:rect inLayer:view.layer ofView:view constrainedToLayer:constrainedView.layer animated:animated];
}
- (void)presentCalloutFromRect:(CGRect)rect inLayer:(CALayer *)layer constrainedToLayer:(CALayer *)constrainedLayer animated:(BOOL)animated {
[self presentCalloutFromRect:rect inLayer:layer ofView:nil constrainedToLayer:constrainedLayer animated:animated];
}
// this private method handles both CALayer and UIView parents depending on what's passed.
- (void)presentCalloutFromRect:(CGRect)rect inLayer:(CALayer *)layer ofView:(UIView *)view constrainedToLayer:(CALayer *)constrainedLayer animated:(BOOL)animated {
// Sanity check: dismiss this callout immediately if it's displayed somewhere
if (self.layer.superlayer) [self dismissCalloutAnimated:NO];
// cancel all animations that may be in progress
[self.layer removeAnimationForKey:@"present"];
[self.layer removeAnimationForKey:@"dismiss"];
// figure out the constrained view's rect in our popup view's coordinate system
CGRect constrainedRect = [constrainedLayer convertRect:constrainedLayer.bounds toLayer:layer];
// apply our edge constraints
constrainedRect = UIEdgeInsetsInsetRect(constrainedRect, self.constrainedInsets);
constrainedRect = CGRectInset(constrainedRect, COMFORTABLE_MARGIN, COMFORTABLE_MARGIN);
// form our subviews based on our content set so far
[self rebuildSubviews];
// apply title/subtitle (if present
self.titleLabel.text = self.title;
self.subtitleLabel.text = self.subtitle;
// size the callout to fit the width constraint as best as possible
self.frameSize = [self sizeThatFits:CGSizeMake(constrainedRect.size.width, self.calloutHeight)];
// how much room do we have in the constraint box, both above and below our target rect?
CGFloat topSpace = CGRectGetMinY(rect) - CGRectGetMinY(constrainedRect);
CGFloat bottomSpace = CGRectGetMaxY(constrainedRect) - CGRectGetMaxY(rect);
// we prefer to point our arrow down.
SMCalloutArrowDirection bestDirection = SMCalloutArrowDirectionDown;
// we'll point it up though if that's the only option you gave us.
if (self.permittedArrowDirection == SMCalloutArrowDirectionUp)
bestDirection = SMCalloutArrowDirectionUp;
// or, if we don't have enough space on the top and have more space on the bottom, and you
// gave us a choice, then pointing up is the better option.
if (self.permittedArrowDirection == SMCalloutArrowDirectionAny && topSpace < self.calloutHeight && bottomSpace > topSpace)
bestDirection = SMCalloutArrowDirectionUp;
self.currentArrowDirection = bestDirection;
// we want to point directly at the horizontal center of the given rect. calculate our "anchor point" in terms of our
// target view's coordinate system. make sure to offset the anchor point as requested if necessary.
CGFloat anchorX = self.calloutOffset.x + CGRectGetMidX(rect);
CGFloat anchorY = self.calloutOffset.y + (bestDirection == SMCalloutArrowDirectionDown ? CGRectGetMinY(rect) : CGRectGetMaxY(rect));
// we prefer to sit centered directly above our anchor
CGFloat calloutX = round(anchorX - self.frameWidth / 2);
// but not if it's going to get too close to the edge of our constraints
if (calloutX < constrainedRect.origin.x)
calloutX = constrainedRect.origin.x;
if (calloutX > constrainedRect.origin.x+constrainedRect.size.width-self.frameWidth)
calloutX = constrainedRect.origin.x+constrainedRect.size.width-self.frameWidth;
// what's the farthest to the left and right that we could point to, given our background image constraints?
CGFloat minPointX = calloutX + self.backgroundView.anchorMargin;
CGFloat maxPointX = calloutX + self.frameWidth - self.backgroundView.anchorMargin;
// we may need to scoot over to the left or right to point at the correct spot
CGFloat adjustX = 0;
if (anchorX < minPointX) adjustX = anchorX - minPointX;
if (anchorX > maxPointX) adjustX = anchorX - maxPointX;
// add the callout to the given layer (or view if possible, to receive touch events)
if (view)
[view addSubview:self];
else
[layer addSublayer:self.layer];
CGPoint calloutOrigin = {
.x = calloutX + adjustX,
.y = bestDirection == SMCalloutArrowDirectionDown ? (anchorY - self.calloutHeight) : anchorY
};
self.frameOrigin = calloutOrigin;
// now set the *actual* anchor point for our layer so that our "popup" animation starts from this point.
CGPoint anchorPoint = [layer convertPoint:CGPointMake(anchorX, anchorY) toLayer:self.layer];
// pass on the anchor point to our background view so it knows where to draw the arrow
self.backgroundView.arrowPoint = anchorPoint;
// adjust it to unit coordinates for the actual layer.anchorPoint property
anchorPoint.x /= self.frameWidth;
anchorPoint.y /= self.frameHeight;
self.layer.anchorPoint = anchorPoint;
// setting the anchor point moves the view a bit, so we need to reset
self.frameOrigin = calloutOrigin;
// make sure our frame is not on half-pixels or else we may be blurry!
CGFloat scale = [UIScreen mainScreen].scale;
self.frameX = floor(self.frameX*scale)/scale;
self.frameY = floor(self.frameY*scale)/scale;
// layout now so we can immediately start animating to the final position if needed
[self setNeedsLayout];
[self layoutIfNeeded];
// if we're outside the bounds of our constraint rect, we'll give our delegate an opportunity to shift us into position.
// consider both our size and the size of our target rect (which we'll assume to be the size of the content you want to scroll into view.
CGRect contentRect = CGRectUnion(self.frame, rect);
CGSize offset = [self offsetToContainRect:contentRect inRect:constrainedRect];
NSTimeInterval delay = 0;
self.popupCancelled = NO; // reset this before calling our delegate below
if ([self.delegate respondsToSelector:@selector(calloutView:delayForRepositionWithSize:)] && !CGSizeEqualToSize(offset, CGSizeZero))
delay = [self.delegate calloutView:(id)self delayForRepositionWithSize:offset];
// there's a chance that user code in the delegate method may have called -dismissCalloutAnimated to cancel things; if that
// happened then we need to bail!
if (self.popupCancelled) return;
// now we want to mask our contents to our background view (if requested) to match the iOS 7 style
self.containerView.layer.mask = self.backgroundView.contentMask;
// if we need to delay, we don't want to be visible while we're delaying, so hide us in preparation for our popup
self.hidden = YES;
// create the appropriate animation, even if we're not animated
CAAnimation *animation = [self animationWithType:self.presentAnimation presenting:YES];
// nuke the duration if no animation requested - we'll still need to "run" the animation to get delays and callbacks
if (!animated)
animation.duration = 0.0000001; // can't be zero or the animation won't "run"
animation.beginTime = CACurrentMediaTime() + delay;
animation.delegate = self;
[self.layer addAnimation:animation forKey:@"present"];
}
- (void)animationDidStart:(CAAnimation *)anim {
BOOL presenting = [[anim valueForKey:@"presenting"] boolValue];
if (presenting) {
if ([_delegate respondsToSelector:@selector(calloutViewWillAppear:)])
[_delegate calloutViewWillAppear:(id)self];
// ok, animation is on, let's make ourselves visible!
self.hidden = NO;
}
else if (!presenting) {
if ([_delegate respondsToSelector:@selector(calloutViewWillDisappear:)])
[_delegate calloutViewWillDisappear:(id)self];
}
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)finished {
BOOL presenting = [[anim valueForKey:@"presenting"] boolValue];
if (presenting && finished) {
if ([_delegate respondsToSelector:@selector(calloutViewDidAppear:)])
[_delegate calloutViewDidAppear:(id)self];
}
else if (!presenting && finished) {
[self removeFromParent];
[self.layer removeAnimationForKey:@"dismiss"];
if ([_delegate respondsToSelector:@selector(calloutViewDidDisappear:)])
[_delegate calloutViewDidDisappear:(id)self];
}
}
- (void)dismissCalloutAnimated:(BOOL)animated {
// cancel all animations that may be in progress
[self.layer removeAnimationForKey:@"present"];
[self.layer removeAnimationForKey:@"dismiss"];
self.popupCancelled = YES;
if (animated) {
CAAnimation *animation = [self animationWithType:self.dismissAnimation presenting:NO];
animation.delegate = self;
[self.layer addAnimation:animation forKey:@"dismiss"];
}
else {
[self removeFromParent];
}
}
- (void)removeFromParent {
if (self.superview)
[self removeFromSuperview];
else {
// removing a layer from a superlayer causes an implicit fade-out animation that we wish to disable.
[CATransaction begin];
[CATransaction setDisableActions:YES];
[self.layer removeFromSuperlayer];
[CATransaction commit];
}
}
- (CAAnimation *)animationWithType:(SMCalloutAnimation)type presenting:(BOOL)presenting {
CAAnimation *animation = nil;
if (type == SMCalloutAnimationBounce) {
CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"opacity"];
fade.duration = 0.23;
fade.fromValue = presenting ? @0.0 : @1.0;
fade.toValue = presenting ? @1.0 : @0.0;
fade.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
CABasicAnimation *bounce = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
bounce.duration = 0.23;
bounce.fromValue = presenting ? @0.7 : @1.0;
bounce.toValue = presenting ? @1.0 : @0.7;
bounce.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.59367f:0.12066f:0.18878f:1.5814f];
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = @[fade, bounce];
group.duration = 0.23;
animation = group;
}
else if (type == SMCalloutAnimationFade) {
CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"opacity"];
fade.duration = 1.0/3.0;
fade.fromValue = presenting ? @0.0 : @1.0;
fade.toValue = presenting ? @1.0 : @0.0;
animation = fade;
}
else if (type == SMCalloutAnimationStretch) {
CABasicAnimation *stretch = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
stretch.duration = 0.1;
stretch.fromValue = presenting ? @0.0 : @1.0;
stretch.toValue = presenting ? @1.0 : @0.0;
animation = stretch;
}
// CAAnimation is KVC compliant, so we can store whether we're presenting for lookup in our delegate methods
[animation setValue:@(presenting) forKey:@"presenting"];
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
return animation;
}
- (void)layoutSubviews {
self.containerView.frame = self.bounds;
self.backgroundView.frame = self.bounds;
// if we're pointing up, we'll need to push almost everything down a bit
CGFloat dy = self.currentArrowDirection == SMCalloutArrowDirectionUp ? TOP_ANCHOR_MARGIN : 0;
self.titleViewOrDefault.frameX = self.innerContentMarginLeft;
self.titleViewOrDefault.frameY = (self.subtitleView || self.subtitle.length ? TITLE_SUB_TOP : TITLE_TOP) + dy;
self.titleViewOrDefault.frameWidth = self.frameWidth - self.innerContentMarginLeft - self.innerContentMarginRight;
self.subtitleViewOrDefault.frameX = self.titleViewOrDefault.frameX;
self.subtitleViewOrDefault.frameY = SUBTITLE_TOP + dy;
self.subtitleViewOrDefault.frameWidth = self.titleViewOrDefault.frameWidth;
self.leftAccessoryView.frameX = self.leftAccessoryHorizontalMargin;
self.leftAccessoryView.frameY = self.leftAccessoryVerticalMargin + dy;
self.rightAccessoryView.frameX = self.frameWidth - self.rightAccessoryHorizontalMargin - self.rightAccessoryView.frameWidth;
self.rightAccessoryView.frameY = self.rightAccessoryVerticalMargin + dy;
if (self.contentView) {
self.contentView.frameX = self.innerContentMarginLeft;
self.contentView.frameY = self.contentViewInset.top + dy;
}
}
#pragma mark - Accessibility
- (NSInteger)accessibilityElementCount {
return (!!self.leftAccessoryView + !!self.titleViewOrDefault +
!!self.subtitleViewOrDefault + !!self.rightAccessoryView);
}
- (id)accessibilityElementAtIndex:(NSInteger)index {
if (index == 0) {
return self.leftAccessoryView ? self.leftAccessoryView : self.titleViewOrDefault;
}
if (index == 1) {
return self.leftAccessoryView ? self.titleViewOrDefault : self.subtitleViewOrDefault;
}
if (index == 2) {
return self.leftAccessoryView ? self.subtitleViewOrDefault : self.rightAccessoryView;
}
if (index == 3) {
return self.leftAccessoryView ? self.rightAccessoryView : nil;
}
return nil;
}
- (NSInteger)indexOfAccessibilityElement:(id)element {
if (element == nil) return NSNotFound;
if (element == self.leftAccessoryView) return 0;
if (element == self.titleViewOrDefault) {
return self.leftAccessoryView ? 1 : 0;
}
if (element == self.subtitleViewOrDefault) {
return self.leftAccessoryView ? 2 : 1;
}
if (element == self.rightAccessoryView) {
return self.leftAccessoryView ? 3 : 2;
}
return NSNotFound;
}
@end
// import this known "private API" from SMCalloutBackgroundView
@interface SMCalloutBackgroundView (EmbeddedImages)
+ (UIImage *)embeddedImageNamed:(NSString *)name;
@end
//
// Callout Background View.
//
@interface SMCalloutMaskedBackgroundView ()
@property (nonatomic, strong) UIView *containerView, *containerBorderView, *arrowView;
@property (nonatomic, strong) UIImageView *arrowImageView, *arrowHighlightedImageView, *arrowBorderView;
@end
static UIImage *blackArrowImage = nil, *normalArrowImageLight = nil, *normalArrowImageDark = nil, *highlightedArrowImageLight = nil, *highlightedArrowImageDark = nil, *arrowBorderImageLight = nil, *arrowBorderImageDark = nil;
static UIColor *normalBackgroundColor, *highlightedBackgroundColor, *borderColor;
@implementation SMCalloutMaskedBackgroundView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIColor *normalBackgroundColorLight = [UIColor whiteColor];
UIColor *normalBackgroundColorDark = [UIColor colorWithWhite:0.2 alpha:1.0];
UIColor *highlightedBackgroundColorLight = [UIColor colorWithWhite:0.85 alpha:1];
UIColor *highlightedBackgroundColorDark = [UIColor colorWithWhite:0.15 alpha:1];
UIColor *borderColorLight = [UIColor colorWithWhite:0 alpha:0.2];
UIColor *borderColorDark = [UIColor colorWithWhite:1 alpha:0.2];
if (@available(iOS 13.0, *)) {
normalBackgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
return normalBackgroundColorLight;
} else {
return normalBackgroundColorDark;
}
}];
highlightedBackgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
return highlightedBackgroundColorLight;
} else {
return highlightedBackgroundColorDark;
}
}];
borderColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
return borderColorLight;
} else {
return borderColorDark;
}
}];
} else {
normalBackgroundColor = normalBackgroundColorLight;
highlightedBackgroundColor = highlightedBackgroundColorLight;
borderColor = borderColorLight;
}
// Here we're mimicking the very particular (and odd) structure of the system callout view.
// The hierarchy and view/layer values were discovered by inspecting map kit using Reveal.app
self.containerView = [UIView new];
self.containerView.backgroundColor = normalBackgroundColor;
self.containerView.alpha = 0.96;
self.containerView.layer.cornerRadius = 8;
self.layer.shadowRadius = 6;
self.layer.shadowOffset = CGSizeMake(0, 4);
self.layer.shadowOpacity = 0.1f;
self.containerBorderView = [UIView new];
self.containerBorderView.layer.borderWidth = 0.5;
self.containerBorderView.layer.cornerRadius = 8.5;
if (!blackArrowImage) {
blackArrowImage = [SMCalloutBackgroundView embeddedImageNamed:@"CalloutArrow"];
normalArrowImageLight = [self image:blackArrowImage withColor:normalBackgroundColorLight];
normalArrowImageDark = [self image:blackArrowImage withColor:normalBackgroundColorDark];
highlightedArrowImageLight = [self image:blackArrowImage withColor:highlightedBackgroundColorLight];
highlightedArrowImageDark = [self image:blackArrowImage withColor:highlightedBackgroundColorDark];
arrowBorderImageLight = [self image:blackArrowImage withColor:borderColorLight];
arrowBorderImageDark = [self image:blackArrowImage withColor:borderColorDark];
}
self.anchorHeight = 13;
self.anchorMargin = 27;
self.arrowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, blackArrowImage.size.width, blackArrowImage.size.height)];
self.arrowView.alpha = 0.96;
self.arrowImageView = [[UIImageView alloc] initWithImage:normalArrowImageLight];
self.arrowHighlightedImageView = [[UIImageView alloc] initWithImage:highlightedArrowImageLight];
self.arrowHighlightedImageView.hidden = YES;
self.arrowBorderView = [[UIImageView alloc] initWithImage:arrowBorderImageLight];
self.arrowBorderView.frameY = 0.5;
[self updateColors];
[self addSubview:self.containerView];
[self.containerView addSubview:self.containerBorderView];
[self addSubview:self.arrowView];
[self.arrowView addSubview:self.arrowBorderView];
[self.arrowView addSubview:self.arrowImageView];
[self.arrowView addSubview:self.arrowHighlightedImageView];
}
return self;
}
// Make sure we relayout our images when our arrow point changes!
- (void)setArrowPoint:(CGPoint)arrowPoint {
[super setArrowPoint:arrowPoint];
[self setNeedsLayout];
}
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
self.containerView.backgroundColor = highlighted ? highlightedBackgroundColor : normalBackgroundColor;
self.arrowImageView.hidden = highlighted;
self.arrowHighlightedImageView.hidden = !highlighted;
}
- (UIImage *)image:(UIImage *)image withColor:(UIColor *)color {
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
CGRect imageRect = (CGRect){.size=image.size};
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, image.size.height);
CGContextScaleCTM(c, 1, -1);
CGContextClipToMask(c, imageRect, image.CGImage);
[color setFill];
CGContextFillRect(c, imageRect);
UIImage *whiteImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return whiteImage;
}
- (void)layoutSubviews {
BOOL pointingUp = self.arrowPoint.y < self.frameHeight/2;
// if we're pointing up, we'll need to push almost everything down a bit
CGFloat dy = pointingUp ? TOP_ANCHOR_MARGIN : 0;
self.containerView.frame = CGRectMake(0, dy, self.frameWidth, self.frameHeight - self.arrowView.frameHeight + 0.5);
self.containerBorderView.frame = CGRectInset(self.containerView.bounds, -0.5, -0.5);
self.arrowView.frameX = round(self.arrowPoint.x - self.arrowView.frameWidth / 2);
if (pointingUp) {
self.arrowView.frameY = 1;
self.arrowView.transform = CGAffineTransformMakeRotation(M_PI);
}
else {
self.arrowView.frameY = self.containerView.frameHeight - 0.5;
self.arrowView.transform = CGAffineTransformIdentity;
}
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
[super traitCollectionDidChange:previousTraitCollection];
[self updateColors];
}
- (void)updateColors {
if (@available(iOS 13.0, *)) {
[self.traitCollection performAsCurrentTraitCollection:^{
if (UITraitCollection.currentTraitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
self.arrowImageView.image = normalArrowImageLight;
self.arrowHighlightedImageView.image = highlightedArrowImageLight;
self.arrowBorderView.image = arrowBorderImageLight;
} else {
self.arrowImageView.image = normalArrowImageDark;
self.arrowHighlightedImageView.image = highlightedArrowImageDark;
self.arrowBorderView.image = arrowBorderImageDark;
}
self.containerBorderView.layer.borderColor = borderColor.CGColor;
}];
} else {
self.arrowImageView.image = normalArrowImageLight;
self.arrowHighlightedImageView.image = highlightedArrowImageLight;
self.arrowBorderView.image = arrowBorderImageLight;
self.containerBorderView.layer.borderColor = borderColor.CGColor;
}
}
- (CALayer *)contentMask {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *maskImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CALayer *layer = [CALayer layer];
layer.frame = self.bounds;
layer.contents = (id)maskImage.CGImage;
return layer;
}
@end
@implementation SMCalloutBackgroundView
+ (UIImage *)embeddedImageNamed:(NSString *)name {
CGFloat screenScale = [UIScreen mainScreen].scale;
if (screenScale > 1.0) {
name = [name stringByAppendingString:@"_2x"];
screenScale = 2.0;
}
SEL selector = NSSelectorFromString(name);
if (![(id)self respondsToSelector:selector]) {
NSLog(@"Could not find an embedded image. Ensure that you've added a class-level method named +%@", name);
return nil;
}
// We need to hush the compiler here - but we know what we're doing!
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
NSString *base64String = [(id)self performSelector:selector];
#pragma clang diagnostic pop
NSData *imageData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
UIImage *rawImage = [UIImage imageWithData:imageData];
return [UIImage imageWithCGImage:rawImage.CGImage scale:screenScale orientation:UIImageOrientationUp];
}
+ (NSString *)CalloutArrow { return @"iVBORw0KGgoAAAANSUhEUgAAACcAAAANCAYAAAAqlHdlAAAAHGlET1QAAAACAAAAAAAAAAcAAAAoAAAABwAAAAYAAADJEgYpIwAAAJVJREFUOBFiYIAAdn5+fkFOTkE5Dg5eW05O3lJOTr6zQPyfDhhoD28pxF5BOZA7gE5ih7oLN8XJyR8MdNwrGjkQaC5/MG7biZDh4OBXBDruLpUdeBdkLhHWE1bCzs6nAnTcUyo58DnIPMK2kqAC6DALIP5JoQNB+i1IsJZ4pcBEm0iJ40D6ibeNDJVAx00k04ETSbUOAAAA//+SwicfAAAAe0lEQVRjYCAdMHNy8u7l5OT7Tzzm3Qu0hpl0q8jQwcPDIwp02B0iHXeHl5dXhAxryNfCzc2tC3TcJwIO/ARSR74tFOjk4uL1BzruHw4H/gPJU2A85Vq5uPjTgY77g+bAPyBxyk2nggkcHPxOnJz8B4AOfAGiQXwqGMsAACGK1kPPMHNBAAAAAElFTkSuQmCC"; }
+ (NSString *)CalloutArrow_2x { return @"iVBORw0KGgoAAAANSUhEUgAAAE4AAAAaCAYAAAAZtWr8AAAACXBIWXMAABYlAAAWJQFJUiTwAAAAHGlET1QAAAACAAAAAAAAAA0AAAAoAAAADQAAAA0AAAFMRh0LGwAAARhJREFUWAnclbENwjAQRZ0mih2fDYgsQEVDxQZMgKjpWYAJkBANI8AGDIEoM0WkzBDRAf8klB44g0OkU1zE3/+9RIpS7VVY730/y/woTWlsjJ9iPcN9pbXfY85auyvm/qcDNmb0e2Z+sk/ZBTthN0oVttX12mJIWeaWEFf+kbySmZQa0msu3nzaGJprTXV3BVLNDG/if7bNOTeAvFP35NGJu39GL7Abb27bFXncVQBZLgJf3jp+ebSWIxZMgrxdvPJoJ4gqHpXgV36ITR46HUGaiNMKB6YQd4lI3gV8qTBjmDhrbQFxVQTyKu4ShjJQap7nE4hrfiiv4Q6B8MLGat1bQNztB/JwZm8Rli5wujFu821xfGZgLPUAAAD//4wvm4gAAAD7SURBVOWXMQ6CMBiFgaFpi6VyBEedXJy4hMQTeBSvRDgJEySegI3EQWOivkZnqUB/k0LyL7R9L++D9G+DwP0TCZGUqCdRlYgUuY9F4JCmqQa0hgBcY7wIItFZMLZYS5l0ruAZbXhs6BIROgmhcoB7OIAHTZUTRqG3wp9xmhqc0aRPQu8YAlwxIbwCEUL6GH9wfDcLXY2HpyvvmkHf9+BcrwCuHQGvNRp9Pl6OY0PPAO42AB7WqMxLKLahpFR7gLv/AA9zPe+gtvAMCIC7WMC7CqEPtrqzmBfHyy3A1V/g1Th27GYBY0BIxrk6Ap65254/VZp30GID9JwteQEZrVMWXqGn8gAAAABJRU5ErkJggg=="; }
@end
//
// Our UIView frame helpers implementation
//
@implementation UIView (SMFrameAdditions)
- (CGPoint)frameOrigin { return self.frame.origin; }
- (void)setFrameOrigin:(CGPoint)origin { self.frame = (CGRect){ .origin=origin, .size=self.frame.size }; }
- (CGFloat)frameX { return self.frame.origin.x; }
- (void)setFrameX:(CGFloat)x { self.frame = (CGRect){ .origin.x=x, .origin.y=self.frame.origin.y, .size=self.frame.size }; }
- (CGFloat)frameY { return self.frame.origin.y; }
- (void)setFrameY:(CGFloat)y { self.frame = (CGRect){ .origin.x=self.frame.origin.x, .origin.y=y, .size=self.frame.size }; }
- (CGSize)frameSize { return self.frame.size; }
- (void)setFrameSize:(CGSize)size { self.frame = (CGRect){ .origin=self.frame.origin, .size=size }; }
- (CGFloat)frameWidth { return self.frame.size.width; }
- (void)setFrameWidth:(CGFloat)width { self.frame = (CGRect){ .origin=self.frame.origin, .size.width=width, .size.height=self.frame.size.height }; }
- (CGFloat)frameHeight { return self.frame.size.height; }
- (void)setFrameHeight:(CGFloat)height { self.frame = (CGRect){ .origin=self.frame.origin, .size.width=self.frame.size.width, .size.height=height }; }
- (CGFloat)frameLeft { return self.frame.origin.x; }
- (void)setFrameLeft:(CGFloat)left { self.frame = (CGRect){ .origin.x=left, .origin.y=self.frame.origin.y, .size.width=fmax(self.frame.origin.x+self.frame.size.width-left,0), .size.height=self.frame.size.height }; }
- (CGFloat)frameTop { return self.frame.origin.y; }
- (void)setFrameTop:(CGFloat)top { self.frame = (CGRect){ .origin.x=self.frame.origin.x, .origin.y=top, .size.width=self.frame.size.width, .size.height=fmax(self.frame.origin.y+self.frame.size.height-top,0) }; }
- (CGFloat)frameRight { return self.frame.origin.x + self.frame.size.width; }
- (void)setFrameRight:(CGFloat)right { self.frame = (CGRect){ .origin=self.frame.origin, .size.width=fmax(right-self.frame.origin.x,0), .size.height=self.frame.size.height }; }
- (CGFloat)frameBottom { return self.frame.origin.y + self.frame.size.height; }
- (void)setFrameBottom:(CGFloat)bottom { self.frame = (CGRect){ .origin=self.frame.origin, .size.width=self.frame.size.width, .size.height=fmax(bottom-self.frame.origin.y,0) }; }
@end