This repository was archived by the owner on Oct 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathSLKTextViewController.m
2448 lines (1912 loc) · 82.7 KB
/
SLKTextViewController.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
//
// SlackTextViewController
// https://github.com/slackhq/SlackTextViewController
//
// Copyright 2014-2016 Slack Technologies, Inc.
// Licence: MIT-Licence
//
#import "SLKTextViewController.h"
#import "SLKInputAccessoryView.h"
#import "UIResponder+SLKAdditions.h"
#import "SLKUIConstants.h"
/** Feature flagged while waiting to implement a more reliable technique. */
#define SLKBottomPanningEnabled 0
#define kSLKAlertViewClearTextTag [NSStringFromClass([SLKTextViewController class]) hash]
NSString * const SLKKeyboardWillShowNotification = @"SLKKeyboardWillShowNotification";
NSString * const SLKKeyboardDidShowNotification = @"SLKKeyboardDidShowNotification";
NSString * const SLKKeyboardWillHideNotification = @"SLKKeyboardWillHideNotification";
NSString * const SLKKeyboardDidHideNotification = @"SLKKeyboardDidHideNotification";
CGFloat const SLKAutoCompletionViewDefaultHeight = 140.0;
@interface SLKTextViewController ()
{
CGPoint _scrollViewOffsetBeforeDragging;
CGFloat _keyboardHeightBeforeDragging;
}
// The shared scrollView pointer, either a tableView or collectionView
@property (nonatomic, weak) UIScrollView *scrollViewProxy;
// A hairline displayed on top of the auto-completion view, to better separate the content from the control.
@property (nonatomic, strong) UIView *autoCompletionHairline;
// Auto-Layout height constraints used for updating their constants
@property (nonatomic, strong) NSLayoutConstraint *scrollViewHC;
@property (nonatomic, strong) NSLayoutConstraint *textInputbarHC;
@property (nonatomic, strong) NSLayoutConstraint *typingIndicatorViewHC;
@property (nonatomic, strong) NSLayoutConstraint *autoCompletionViewHC;
@property (nonatomic, strong) NSLayoutConstraint *keyboardHC;
// YES if the user is moving the keyboard with a gesture
@property (nonatomic, assign, getter = isMovingKeyboard) BOOL movingKeyboard;
// YES if the view controller did appear and everything is finished configurating. This allows blocking some layout animations among other things.
@property (nonatomic, getter=isViewVisible) BOOL viewVisible;
// YES if the view controller's view's size is changing by its parent (i.e. when its window rotates or is resized)
@property (nonatomic, getter = isTransitioning) BOOL transitioning;
// Optional classes to be used instead of the default ones.
@property (nonatomic, strong) Class textViewClass;
@property (nonatomic, strong) Class typingIndicatorViewClass;
@end
@implementation SLKTextViewController
@synthesize tableView = _tableView;
@synthesize collectionView = _collectionView;
@synthesize scrollView = _scrollView;
@synthesize typingIndicatorProxyView = _typingIndicatorProxyView;
@synthesize textInputbar = _textInputbar;
@synthesize autoCompletionView = _autoCompletionView;
@synthesize autoCompleting = _autoCompleting;
@synthesize scrollViewProxy = _scrollViewProxy;
@synthesize presentedInPopover = _presentedInPopover;
#pragma mark - Initializer
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [self initWithTableViewStyle:UITableViewStylePlain];
}
- (instancetype)init
{
return [self initWithTableViewStyle:UITableViewStylePlain];
}
- (instancetype)initWithTableViewStyle:(UITableViewStyle)style
{
NSAssert([self class] != [SLKTextViewController class], @"Oops! You must subclass SLKTextViewController.");
NSAssert(style == UITableViewStylePlain || style == UITableViewStyleGrouped, @"Oops! You must pass a valid UITableViewStyle.");
if (self = [super initWithNibName:nil bundle:nil])
{
self.scrollViewProxy = [self tableViewWithStyle:style];
[self slk_commonInit];
}
return self;
}
- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout
{
NSAssert([self class] != [SLKTextViewController class], @"Oops! You must subclass SLKTextViewController.");
NSAssert([layout isKindOfClass:[UICollectionViewLayout class]], @"Oops! You must pass a valid UICollectionViewLayout object.");
if (self = [super initWithNibName:nil bundle:nil])
{
self.scrollViewProxy = [self collectionViewWithLayout:layout];
[self slk_commonInit];
}
return self;
}
- (instancetype)initWithScrollView:(UIScrollView *)scrollView
{
NSAssert([self class] != [SLKTextViewController class], @"Oops! You must subclass SLKTextViewController.");
NSAssert([scrollView isKindOfClass:[UIScrollView class]], @"Oops! You must pass a valid UIScrollView object.");
if (self = [super initWithNibName:nil bundle:nil])
{
_scrollView = scrollView;
_scrollView.translatesAutoresizingMaskIntoConstraints = NO; // Makes sure the scrollView plays nice with auto-layout
self.scrollViewProxy = _scrollView;
[self slk_commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)decoder
{
NSAssert([self class] != [SLKTextViewController class], @"Oops! You must subclass SLKTextViewController.");
NSAssert([decoder isKindOfClass:[NSCoder class]], @"Oops! You must pass a valid decoder object.");
if (self = [super initWithCoder:decoder])
{
UITableViewStyle tableViewStyle = [[self class] tableViewStyleForCoder:decoder];
UICollectionViewLayout *collectionViewLayout = [[self class] collectionViewLayoutForCoder:decoder];
if ([collectionViewLayout isKindOfClass:[UICollectionViewLayout class]]) {
self.scrollViewProxy = [self collectionViewWithLayout:collectionViewLayout];
}
else {
self.scrollViewProxy = [self tableViewWithStyle:tableViewStyle];
}
[self slk_commonInit];
}
return self;
}
- (void)slk_commonInit
{
[self slk_registerNotifications];
self.bounces = YES;
self.inverted = YES;
self.shakeToClearEnabled = NO;
self.keyboardPanningEnabled = YES;
self.shouldClearTextAtRightButtonPress = YES;
self.shouldScrollToBottomAfterKeyboardShows = NO;
self.automaticallyAdjustsScrollViewInsets = YES;
self.extendedLayoutIncludesOpaqueBars = YES;
}
#pragma mark - View lifecycle
- (void)loadView
{
[super loadView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:self.scrollViewProxy];
[self.view addSubview:self.autoCompletionView];
[self.view addSubview:self.typingIndicatorProxyView];
[self.view addSubview:self.textInputbar];
[self slk_setupViewConstraints];
[self slk_registerKeyCommands];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Invalidates this flag when the view appears
self.textView.didNotResignFirstResponder = NO;
// Forces laying out the recently added subviews and update their constraints
[self.view layoutIfNeeded];
[UIView performWithoutAnimation:^{
// Reloads any cached text
[self slk_reloadTextView];
}];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.scrollViewProxy flashScrollIndicators];
self.viewVisible = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Stops the keyboard from being dismissed during the navigation controller's "swipe-to-pop"
self.textView.didNotResignFirstResponder = self.isMovingFromParentViewController;
self.viewVisible = NO;
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
// Caches the text before it's too late!
[self cacheTextView];
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
[self slk_adjustContentConfigurationIfNeeded];
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
}
- (void)viewSafeAreaInsetsDidChange
{
[super viewSafeAreaInsetsDidChange];
[self slk_updateViewConstraints];
}
#pragma mark - Getters
+ (UITableViewStyle)tableViewStyleForCoder:(NSCoder *)decoder
{
return UITableViewStylePlain;
}
+ (UICollectionViewLayout *)collectionViewLayoutForCoder:(NSCoder *)decoder
{
return nil;
}
- (UITableView *)tableViewWithStyle:(UITableViewStyle)style
{
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:style];
_tableView.translatesAutoresizingMaskIntoConstraints = NO;
_tableView.scrollsToTop = YES;
_tableView.dataSource = self;
_tableView.delegate = self;
_tableView.clipsToBounds = NO;
[self slk_updateInsetAdjustmentBehavior];
}
return _tableView;
}
- (UICollectionView *)collectionViewWithLayout:(UICollectionViewLayout *)layout
{
if (!_collectionView) {
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
_collectionView.backgroundColor = [UIColor whiteColor];
_collectionView.translatesAutoresizingMaskIntoConstraints = NO;
_collectionView.scrollsToTop = YES;
_collectionView.dataSource = self;
_collectionView.delegate = self;
}
return _collectionView;
}
- (UITableView *)autoCompletionView
{
if (!_autoCompletionView) {
_autoCompletionView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
_autoCompletionView.translatesAutoresizingMaskIntoConstraints = NO;
_autoCompletionView.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1.0];
_autoCompletionView.scrollsToTop = NO;
_autoCompletionView.dataSource = self;
_autoCompletionView.delegate = self;
#ifdef __IPHONE_9_0
if ([_autoCompletionView respondsToSelector:@selector(cellLayoutMarginsFollowReadableWidth)]) {
_autoCompletionView.cellLayoutMarginsFollowReadableWidth = NO;
}
#endif
CGRect rect = CGRectZero;
rect.size = CGSizeMake(CGRectGetWidth(self.view.frame), 0.5);
_autoCompletionHairline = [[UIView alloc] initWithFrame:rect];
_autoCompletionHairline.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_autoCompletionHairline.backgroundColor = _autoCompletionView.separatorColor;
[_autoCompletionView addSubview:_autoCompletionHairline];
}
return _autoCompletionView;
}
- (SLKTextInputbar *)textInputbar
{
if (!_textInputbar) {
_textInputbar = [[SLKTextInputbar alloc] initWithTextViewClass:self.textViewClass];
_textInputbar.translatesAutoresizingMaskIntoConstraints = NO;
[_textInputbar.leftButton addTarget:self action:@selector(didPressLeftButton:) forControlEvents:UIControlEventTouchUpInside];
[_textInputbar.rightButton addTarget:self action:@selector(didPressRightButton:) forControlEvents:UIControlEventTouchUpInside];
[_textInputbar.editorLeftButton addTarget:self action:@selector(didCancelTextEditing:) forControlEvents:UIControlEventTouchUpInside];
[_textInputbar.editorRightButton addTarget:self action:@selector(didCommitTextEditing:) forControlEvents:UIControlEventTouchUpInside];
_textInputbar.textView.delegate = self;
_verticalPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(slk_didPanTextInputBar:)];
_verticalPanGesture.delegate = self;
[_textInputbar addGestureRecognizer:self.verticalPanGesture];
}
return _textInputbar;
}
- (UIView <SLKTypingIndicatorProtocol> *)typingIndicatorProxyView
{
if (!_typingIndicatorProxyView) {
Class class = self.typingIndicatorViewClass ? : [SLKTypingIndicatorView class];
_typingIndicatorProxyView = [[class alloc] init];
_typingIndicatorProxyView.translatesAutoresizingMaskIntoConstraints = NO;
_typingIndicatorProxyView.hidden = YES;
[_typingIndicatorProxyView addObserver:self forKeyPath:@"visible" options:NSKeyValueObservingOptionNew context:nil];
}
return _typingIndicatorProxyView;
}
- (SLKTypingIndicatorView *)typingIndicatorView
{
if ([_typingIndicatorProxyView isKindOfClass:[SLKTypingIndicatorView class]]) {
return (SLKTypingIndicatorView *)self.typingIndicatorProxyView;
}
return nil;
}
- (BOOL)isPresentedInPopover
{
return _presentedInPopover && SLK_IS_IPAD;
}
- (BOOL)isTextInputbarHidden
{
return _textInputbar.hidden;
}
- (SLKTextView *)textView
{
return _textInputbar.textView;
}
- (UIButton *)leftButton
{
return _textInputbar.leftButton;
}
- (UIButton *)rightButton
{
return _textInputbar.rightButton;
}
- (UIModalPresentationStyle)modalPresentationStyle
{
if (self.navigationController) {
return self.navigationController.modalPresentationStyle;
}
return [super modalPresentationStyle];
}
- (CGFloat)slk_appropriateKeyboardHeightFromNotification:(NSNotification *)notification
{
// Let's first detect keyboard special states such as external keyboard, undocked or split layouts.
[self slk_detectKeyboardStatesInNotification:notification];
if ([self ignoreTextInputbarAdjustment]) {
return [self slk_appropriateBottomMargin];
}
CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
return [self slk_appropriateKeyboardHeightFromRect:keyboardRect];
}
- (CGFloat)slk_appropriateKeyboardHeightFromRect:(CGRect)rect
{
CGRect keyboardRect = [self.view convertRect:rect fromView:nil];
CGFloat viewHeight = CGRectGetHeight(self.view.bounds);
CGFloat keyboardMinY = CGRectGetMinY(keyboardRect);
CGFloat keyboardHeight = MAX(0.0, viewHeight - keyboardMinY);
CGFloat bottomMargin = [self slk_appropriateBottomMargin];
// When the keyboard height is zero, we can assume there is no keyboard visible
// In that case, let's see if there are any other views outside of the view hiearchy
// requiring to adjust the text input bottom margin
if (keyboardHeight < bottomMargin) {
keyboardHeight = bottomMargin;
}
return keyboardHeight;
}
- (CGFloat)slk_appropriateBottomMargin
{
// A bottom margin is required if the view is extended out of it bounds
if ((self.edgesForExtendedLayout & UIRectEdgeBottom) > 0) {
UITabBar *tabBar = self.tabBarController.tabBar;
// Considers the bottom tab bar, unless it will be hidden
if (tabBar && !tabBar.hidden && !self.hidesBottomBarWhenPushed) {
return CGRectGetHeight(tabBar.frame);
}
}
// A bottom margin is required for iPhone X
if (@available(iOS 11.0, *)) {
if (!self.textInputbar.isHidden) {
return self.view.safeAreaInsets.bottom;
}
}
return 0.0;
}
- (CGFloat)slk_appropriateScrollViewHeight
{
CGFloat scrollViewHeight = CGRectGetHeight(self.view.bounds);
scrollViewHeight -= self.keyboardHC.constant;
scrollViewHeight -= self.textInputbarHC.constant;
scrollViewHeight -= self.autoCompletionViewHC.constant;
scrollViewHeight -= self.typingIndicatorViewHC.constant;
if (scrollViewHeight < 0) return 0;
else return scrollViewHeight;
}
- (CGFloat)slk_topBarsHeight
{
// No need to adjust if the edge isn't available
if ((self.edgesForExtendedLayout & UIRectEdgeTop) == 0) {
return 0.0;
}
CGFloat topBarsHeight = CGRectGetHeight(self.navigationController.navigationBar.frame);
if ((SLK_IS_IPHONE && SLK_IS_LANDSCAPE && SLK_IS_IOS8_AND_HIGHER) ||
(SLK_IS_IPAD && self.modalPresentationStyle == UIModalPresentationFormSheet) ||
self.isPresentedInPopover) {
return topBarsHeight;
}
topBarsHeight += CGRectGetHeight([UIApplication sharedApplication].statusBarFrame);
return topBarsHeight;
}
- (NSString *)slk_appropriateKeyboardNotificationName:(NSNotification *)notification
{
NSString *name = notification.name;
if ([name isEqualToString:UIKeyboardWillShowNotification]) {
return SLKKeyboardWillShowNotification;
}
if ([name isEqualToString:UIKeyboardWillHideNotification]) {
return SLKKeyboardWillHideNotification;
}
if ([name isEqualToString:UIKeyboardDidShowNotification]) {
return SLKKeyboardDidShowNotification;
}
if ([name isEqualToString:UIKeyboardDidHideNotification]) {
return SLKKeyboardDidHideNotification;
}
return nil;
}
- (SLKKeyboardStatus)slk_keyboardStatusForNotification:(NSNotification *)notification
{
NSString *name = notification.name;
if ([name isEqualToString:UIKeyboardWillShowNotification]) {
return SLKKeyboardStatusWillShow;
}
if ([name isEqualToString:UIKeyboardDidShowNotification]) {
return SLKKeyboardStatusDidShow;
}
if ([name isEqualToString:UIKeyboardWillHideNotification]) {
return SLKKeyboardStatusWillHide;
}
if ([name isEqualToString:UIKeyboardDidHideNotification]) {
return SLKKeyboardStatusDidHide;
}
return -1;
}
- (BOOL)slk_isIllogicalKeyboardStatus:(SLKKeyboardStatus)newStatus
{
if ((self.keyboardStatus == SLKKeyboardStatusDidHide && newStatus == SLKKeyboardStatusWillShow) ||
(self.keyboardStatus == SLKKeyboardStatusWillShow && newStatus == SLKKeyboardStatusDidShow) ||
(self.keyboardStatus == SLKKeyboardStatusDidShow && newStatus == SLKKeyboardStatusWillHide) ||
(self.keyboardStatus == SLKKeyboardStatusWillHide && newStatus == SLKKeyboardStatusDidHide)) {
return NO;
}
return YES;
}
#pragma mark - Setters
- (void)setEdgesForExtendedLayout:(UIRectEdge)rectEdge
{
if (self.edgesForExtendedLayout == rectEdge) {
return;
}
[super setEdgesForExtendedLayout:rectEdge];
[self slk_updateViewConstraints];
}
- (void)setScrollViewProxy:(UIScrollView *)scrollView
{
if ([_scrollViewProxy isEqual:scrollView]) {
return;
}
_singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(slk_didTapScrollView:)];
_singleTapGesture.delegate = self;
[_singleTapGesture requireGestureRecognizerToFail:scrollView.panGestureRecognizer];
[scrollView addGestureRecognizer:self.singleTapGesture];
[scrollView.panGestureRecognizer addTarget:self action:@selector(slk_didPanTextInputBar:)];
_scrollViewProxy = scrollView;
}
- (void)setAutoCompleting:(BOOL)autoCompleting
{
if (_autoCompleting == autoCompleting) {
return;
}
_autoCompleting = autoCompleting;
self.scrollViewProxy.scrollEnabled = !autoCompleting;
}
- (void)setInverted:(BOOL)inverted
{
if (_inverted == inverted) {
return;
}
_inverted = inverted;
[self slk_updateInsetAdjustmentBehavior];
self.scrollViewProxy.transform = inverted ? CGAffineTransformMake(1, 0, 0, -1, 0, 0) : CGAffineTransformIdentity;
}
- (void)setBounces:(BOOL)bounces
{
_bounces = bounces;
_textInputbar.bounces = bounces;
}
- (void)slk_updateInsetAdjustmentBehavior
{
// Deactivate automatic scrollView adjustment for inverted table view
if (@available(iOS 11.0, *)) {
if (self.isInverted) {
_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
}
}
}
- (BOOL)slk_updateKeyboardStatus:(SLKKeyboardStatus)status
{
// Skips if trying to update the same status
if (_keyboardStatus == status) {
return NO;
}
// Skips illogical conditions
// Forces the keyboard status when didHide to avoid any inconsistency.
if (status != SLKKeyboardStatusDidHide && [self slk_isIllogicalKeyboardStatus:status]) {
return NO;
}
_keyboardStatus = status;
[self didChangeKeyboardStatus:status];
return YES;
}
#pragma mark - Public & Subclassable Methods
- (void)presentKeyboard:(BOOL)animated
{
// Skips if already first responder
if ([self.textView isFirstResponder]) {
return;
}
if (!animated) {
[UIView performWithoutAnimation:^{
[self.textView becomeFirstResponder];
}];
}
else {
[self.textView becomeFirstResponder];
}
}
- (void)dismissKeyboard:(BOOL)animated
{
// Dismisses the keyboard from any first responder in the window.
if (![self.textView isFirstResponder] && self.keyboardHC.constant > 0) {
[self.view.window endEditing:NO];
}
if (!animated) {
[UIView performWithoutAnimation:^{
[self.textView resignFirstResponder];
}];
}
else {
[self.textView resignFirstResponder];
}
}
- (BOOL)forceTextInputbarAdjustmentForResponder:(UIResponder *)responder
{
return NO;
}
- (BOOL)ignoreTextInputbarAdjustment
{
if (self.isExternalKeyboardDetected || self.isKeyboardUndocked) {
return YES;
}
return NO;
}
- (void)didChangeKeyboardStatus:(SLKKeyboardStatus)status
{
// No implementation here. Meant to be overriden in subclass.
}
- (void)textWillUpdate
{
// No implementation here. Meant to be overriden in subclass.
}
- (void)textDidUpdate:(BOOL)animated
{
if (self.isTextInputbarHidden) {
return;
}
CGFloat inputbarHeight = _textInputbar.appropriateHeight;
_textInputbar.rightButton.enabled = [self canPressRightButton];
_textInputbar.editorRightButton.enabled = [self canPressRightButton];
if (inputbarHeight != self.textInputbarHC.constant)
{
CGFloat inputBarHeightDelta = inputbarHeight - self.textInputbarHC.constant;
CGPoint newOffset = CGPointMake(0, self.scrollViewProxy.contentOffset.y + inputBarHeightDelta);
self.textInputbarHC.constant = inputbarHeight;
self.scrollViewHC.constant = [self slk_appropriateScrollViewHeight];
if (animated) {
BOOL bounces = self.bounces && [self.textView isFirstResponder];
__weak typeof(self) weakSelf = self;
[self.view slk_animateLayoutIfNeededWithBounce:bounces
options:UIViewAnimationOptionCurveEaseInOut|UIViewAnimationOptionLayoutSubviews|UIViewAnimationOptionBeginFromCurrentState
animations:^{
if (!self.isInverted) {
self.scrollViewProxy.contentOffset = newOffset;
}
if (weakSelf.textInputbar.isEditing) {
[weakSelf.textView slk_scrollToCaretPositonAnimated:NO];
}
}];
}
else {
[self.view layoutIfNeeded];
}
}
// Toggles auto-correction if requiered
[self slk_enableTypingSuggestionIfNeeded];
}
- (void)textSelectionDidChange
{
// The text view must be first responder
if (![self.textView isFirstResponder] || self.keyboardStatus != SLKKeyboardStatusDidShow) {
return;
}
// Skips there is a real text selection
if (self.textView.isTrackpadEnabled) {
return;
}
if (self.textView.selectedRange.length > 0) {
if (self.isAutoCompleting && [self shouldProcessTextForAutoCompletion]) {
[self cancelAutoCompletion];
}
return;
}
// Process the text at every caret movement
[self slk_processTextForAutoCompletion];
}
- (BOOL)canPressRightButton
{
NSString *text = [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (text.length > 0 && ![_textInputbar limitExceeded]) {
return YES;
}
return NO;
}
- (void)didPressLeftButton:(id)sender
{
// No implementation here. Meant to be overriden in subclass.
}
- (void)didPressRightButton:(id)sender
{
if (self.shouldClearTextAtRightButtonPress) {
// Clears the text and the undo manager
[self.textView slk_clearText:YES];
}
// Clears cache
[self clearCachedText];
}
- (void)editText:(NSString *)text
{
NSAttributedString *attributedText = [self.textView slk_defaultAttributedStringForText:text];
[self editAttributedText:attributedText];
}
- (void)editAttributedText:(NSAttributedString *)attributedText
{
if (![_textInputbar canEditText:attributedText.string]) {
return;
}
// Caches the current text, in case the user cancels the edition
[self slk_cacheAttributedTextToDisk:self.textView.attributedText];
[_textInputbar beginTextEditing];
// Setting the text after calling -beginTextEditing is safer
[self.textView setAttributedText:attributedText];
[self.textView slk_scrollToCaretPositonAnimated:YES];
// Brings up the keyboard if needed
[self presentKeyboard:YES];
}
- (void)didCommitTextEditing:(id)sender
{
if (!_textInputbar.isEditing) {
return;
}
[_textInputbar endTextEdition];
// Clears the text and but not the undo manager
[self.textView slk_clearText:NO];
}
- (void)didCancelTextEditing:(id)sender
{
if (!_textInputbar.isEditing) {
return;
}
[_textInputbar endTextEdition];
// Clears the text and but not the undo manager
[self.textView slk_clearText:NO];
// Restores any previous cached text before entering in editing mode
[self slk_reloadTextView];
}
- (BOOL)canShowTypingIndicator
{
// Don't show if the text is being edited or auto-completed.
if (_textInputbar.isEditing || self.isAutoCompleting) {
return NO;
}
return YES;
}
- (CGFloat)heightForAutoCompletionView
{
return 0.0;
}
- (CGFloat)maximumHeightForAutoCompletionView
{
CGFloat maxiumumHeight = SLKAutoCompletionViewDefaultHeight;
if (self.isAutoCompleting) {
CGFloat scrollViewHeight = self.scrollViewHC.constant;
scrollViewHeight -= [self slk_topBarsHeight];
if (scrollViewHeight < maxiumumHeight) {
maxiumumHeight = scrollViewHeight;
}
}
return maxiumumHeight;
}
- (void)didPasteMediaContent:(NSDictionary *)userInfo
{
// No implementation here. Meant to be overriden in subclass.
}
- (void)willRequestUndo
{
NSString *title = NSLocalizedString(@"Undo Typing", nil);
NSString *acceptTitle = NSLocalizedString(@"Undo", nil);
NSString *cancelTitle = NSLocalizedString(@"Cancel", nil);
#ifdef __IPHONE_8_0
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:acceptTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// Clears the text but doesn't clear the undo manager
if (self.shakeToClearEnabled) {
[self.textView slk_clearText:NO];
}
}]];
[alertController addAction:[UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:NULL]];
[self presentViewController:alertController animated:YES completion:nil];
#else
UIAlertView *alert = [UIAlertView new];
[alert setTitle:title];
[alert addButtonWithTitle:acceptTitle];
[alert addButtonWithTitle:cancelTitle];
[alert setCancelButtonIndex:1];
[alert setTag:kSLKAlertViewClearTextTag];
[alert setDelegate:self];
[alert show];
#endif
}
- (void)setTextInputbarHidden:(BOOL)hidden
{
[self setTextInputbarHidden:hidden animated:NO];
}
- (void)setTextInputbarHidden:(BOOL)hidden animated:(BOOL)animated
{
if (self.isTextInputbarHidden == hidden) {
return;
}
_textInputbar.hidden = hidden;
if (@available(iOS 11.0, *)) {
[self viewSafeAreaInsetsDidChange];
}
__weak typeof(self) weakSelf = self;
void (^animations)(void) = ^void(){
weakSelf.textInputbarHC.constant = hidden ? 0.0 : weakSelf.textInputbar.appropriateHeight;
[weakSelf.view layoutIfNeeded];
};
void (^completion)(BOOL finished) = ^void(BOOL finished){
if (hidden) {
[self dismissKeyboard:YES];
}
};
if (animated) {
[UIView animateWithDuration:0.25 animations:animations completion:completion];
}
else {
animations();
completion(NO);
}
}
#pragma mark - Private Methods
- (void)slk_didPanTextInputBar:(UIPanGestureRecognizer *)gesture
{
// Textinput dragging isn't supported when
if (!self.view.window || !self.keyboardPanningEnabled ||
[self ignoreTextInputbarAdjustment] || self.isPresentedInPopover) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self slk_handlePanGestureRecognizer:gesture];
});
}
- (void)slk_handlePanGestureRecognizer:(UIPanGestureRecognizer *)gesture
{
// Local variables
static CGPoint startPoint;
static CGRect originalFrame;
static BOOL dragging = NO;
static BOOL presenting = NO;
__block UIView *keyboardView = [_textInputbar.inputAccessoryView keyboardViewProxy];
// When no keyboard view has been detecting, let's skip any handling.
if (!keyboardView) {
return;
}
// Dynamic variables
CGPoint gestureLocation = [gesture locationInView:self.view];
CGPoint gestureVelocity = [gesture velocityInView:self.view];
CGFloat keyboardMaxY = CGRectGetHeight(SLKKeyWindowBounds());
CGFloat keyboardMinY = keyboardMaxY - CGRectGetHeight(keyboardView.frame);
// Skips this if it's not the expected textView.
// Checking the keyboard height constant helps to disable the view constraints update on iPad when the keyboard is undocked.
// Checking the keyboard status allows to keep the inputAccessoryView valid when still reacing the bottom of the screen.
CGFloat bottomMargin = [self slk_appropriateBottomMargin];
if (![self.textView isFirstResponder] || (self.keyboardHC.constant == bottomMargin && self.keyboardStatus == SLKKeyboardStatusDidHide)) {
#if SLKBottomPanningEnabled
if ([gesture.view isEqual:self.scrollViewProxy]) {
if (gestureVelocity.y > 0) {
return;
}
else if ((self.isInverted && ![self.scrollViewProxy slk_isAtTop]) || (!self.isInverted && ![self.scrollViewProxy slk_isAtBottom])) {
return;
}
}
presenting = YES;
#else
if ([gesture.view isEqual:_textInputbar] && gestureVelocity.y < 0) {
[self presentKeyboard:YES];
}
return;
#endif
}