forked from hackiftekhar/IQKeyboardManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIQKeyboardManager.m
executable file
·1028 lines (850 loc) · 38.8 KB
/
IQKeyboardManager.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
//
// KeyboardManager.m
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-14 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "IQKeyboardManager.h"
#import "IQUIView+Hierarchy.h"
#import "IQUIView+IQKeyboardToolbar.h"
#import "IQUIWindow+Hierarchy.h"
#import "IQNSArray+Sort.h"
#import "IQToolbar.h"
#import "IQBarButtonItem.h"
#import "IQKeyboardManagerConstantsInternal.h"
#import <UIKit/UITapGestureRecognizer.h>
#import <UIKit/UITextField.h>
#import <UIKit/UITextView.h>
#import <UIKit/UIViewController.h>
#import <UIKit/UITableView.h>
@interface IQKeyboardManager (RemoveCompilerWarning)
//Remove compiler warning
-(void)previousAction:(id)segmentedControl;
-(void)nextAction:(id)segmentedControl;
-(void)doneAction:(IQBarButtonItem*)barButton;
@end
@interface IQKeyboardManager()<UIGestureRecognizerDelegate>
/*!
@property keyWindow
@abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app.
*/
@property(nonatomic, strong, readonly) UIWindow *keyWindow;
// Private helper methods
- (void)adjustFrame;
- (void)addToolbarIfRequired;
- (void)removeToolbarIfRequired;
// Private function to manipulate RootViewController's frame with animation.
- (void)setRootViewFrame:(CGRect)frame;
// Notification methods
- (void)keyboardWillShow:(NSNotification*)aNotification;
- (void)keyboardWillHide:(NSNotification*)aNotification;
- (void)textFieldViewDidBeginEditing:(NSNotification*)notification;
- (void)textFieldViewDidEndEditing:(NSNotification*)notification;
- (void)textFieldViewDidChange:(NSNotification*)notification;
- (void)tapRecognized:(UITapGestureRecognizer*)gesture;
@end
@implementation IQKeyboardManager
{
@package
/*! Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
BOOL isKeyboardShowing;
/*! To save rootViewController.view.frame. */
CGRect topViewBeginRect;
/*! To save keyboard animation duration. */
CGFloat animationDuration;
/*! To mimic the keyboard animation */
NSInteger animationCurve;
/*! To save UITextField/UITextView object voa textField/textView notifications. */
__weak UIView *_textFieldView;
/*! To save keyboard size. */
CGSize kbSize;
/*! To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
NSNotification *kbShowNotification;
/*! Variable to save lastScrollView that was scrolled. */
__weak UIScrollView *lastScrollView;
/*! LastScrollView's initial contentOffset. */
CGPoint startingContentOffset;
/*! TapGesture to resign keyboard on view's touch. */
UITapGestureRecognizer *tapGesture;
/*! used with canAdjustTextView boolean. */
CGRect textFieldViewIntialFrame;
}
//KeyWindow
@synthesize keyWindow = _keyWindow;
//UIKeyboard handling
@synthesize enable = _enable;
@synthesize keyboardDistanceFromTextField = _keyboardDistanceFromTextField;
@synthesize overrideKeyboardAppearance = _overrideKeyboardAppearance;
@synthesize keyboardAppearance = _keyboardAppearance;
//IQToolbar handling
@synthesize enableAutoToolbar = _enableAutoToolbar;
@synthesize toolbarManageBehaviour = _toolbarManageBehaviour;
@synthesize shouldToolbarUsesTextFieldTintColor = _shouldToolbarUsesTextFieldTintColor;
@synthesize shouldShowTextFieldPlaceholder = _shouldShowTextFieldPlaceholder;
@synthesize placeholderFont = _placeholderFont;
//TextView handling
@synthesize canAdjustTextView = _canAdjustTextView;
//Resign handling
@synthesize shouldResignOnTouchOutside = _shouldResignOnTouchOutside;
//Sound handling
@synthesize shouldPlayInputClicks = _shouldPlayInputClicks;
//Animation handling
@synthesize shouldAdoptDefaultKeyboardAnimation = _shouldAdoptDefaultKeyboardAnimation;
#pragma mark - Initializing functions
/*! Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. */
+(void)load
{
[super load];
//Enabling Keyboard Manager.
[[IQKeyboardManager sharedManager] setEnable:YES];
}
/* Singleton Object Initialization. */
-(id)init
{
if (self = [super init])
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Registering for keyboard notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
// Registering for textField notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
// Registering for textView notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
//Creating gesture for @shouldResignOnTouchOutside
tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
[tapGesture setDelegate:self];
// Default settings
[self setKeyboardDistanceFromTextField:10.0];
animationDuration = 0.25;
//Setting it's initial values
_enable = NO;
[self setCanAdjustTextView:NO];
[self setShouldPlayInputClicks:NO];
[self setShouldResignOnTouchOutside:NO];
[self setShouldToolbarUsesTextFieldTintColor:NO];
[self setOverrideKeyboardAppearance:NO];
[self setKeyboardAppearance:UIKeyboardAppearanceDefault];
[self setEnableAutoToolbar:YES];
[self setShouldShowTextFieldPlaceholder:YES];
[self setShouldAdoptDefaultKeyboardAnimation:YES];
[self setToolbarManageBehaviour:IQAutoToolbarBySubviews];
_keyWindow = [self keyWindow];
});
}
return self;
}
/* Automatically called from the `+(void)load` method. */
+ (IQKeyboardManager*)sharedManager
{
//Singleton instance
static IQKeyboardManager *kbManager;
//Dispatching it once.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Initializing keyboard manger.
kbManager = [[self alloc] init];
});
//Returning kbManager.
return kbManager;
}
#pragma mark - Dealloc
-(void)dealloc
{
// Disable the keyboard manager.
[self setEnable:NO];
//Removing notification observers on dealloc.
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Property functions
-(void)setEnable:(BOOL)enable
{
// If not enabled, enable it.
if (enable == YES && _enable == NO)
{
//Setting NO to _enable.
_enable = enable;
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if (kbShowNotification) [self keyboardWillShow:kbShowNotification];
#if IQKEYBOARDMANAGER_DEBUG
NSLog(@"%@",IQLocalizedString(@"IQKeyboardManager enabled", nil));
#endif
}
//If not disable, desable it.
else if (enable == NO && _enable == YES)
{
//Sending a fake notification for keyboardWillHide to retain view's original frame.
[self keyboardWillHide:nil];
//Setting NO to _enable.
_enable = enable;
#if IQKEYBOARDMANAGER_DEBUG
NSLog(@"%@",IQLocalizedString(@"IQKeyboardManager disabled", nil));
#endif
}
//If already disabled.
else if (enable == NO && _enable == NO)
{
#if IQKEYBOARDMANAGER_DEBUG
NSLog(@"%@",IQLocalizedString(@"IQKeyboardManager already disabled", nil));
#endif
}
//If already enabled.
else if (enable == YES && _enable == YES)
{
#if IQKEYBOARDMANAGER_DEBUG
NSLog(@"%@",IQLocalizedString(@"IQKeyboardManager already enabled", nil));
#endif
}
}
//Is enabled
-(BOOL)isEnabled
{
return _enable;
}
// Setting keyboard distance from text field.
-(void)setKeyboardDistanceFromTextField:(CGFloat)keyboardDistanceFromTextField
{
//Can't be less than zero. Minimum is zero.
_keyboardDistanceFromTextField = MAX(keyboardDistanceFromTextField, 0);
}
/*! Getting keyWindow. */
-(UIWindow *)keyWindow
{
//If it is not initialized then return [[UIApplication sharedApplication] keyWindow], otherwise return it.
if (_keyWindow == nil) _keyWindow = [[UIApplication sharedApplication] keyWindow];
return _keyWindow;
}
#pragma mark - Private Methods
/* Helper function to manipulate RootViewController's frame with animation. */
-(void)setRootViewFrame:(CGRect)frame
{
// Getting topMost ViewController.
UIViewController *controller = [[self keyWindow] topMostController];
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
if (IQ_IS_IOS8_OR_GREATER)
{
frame.size = controller.view.size;
}
// If can't get rootViewController then printing warning to user.
if (controller == nil) NSLog(@"%@",IQLocalizedString(@"You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager", nil));
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
// Setting it's new frame
[controller.view setFrame:frame];
} completion:^(BOOL finished) {
}];
}
/* UIKeyboard Did show. Adjusting RootViewController's frame according to device orientation. */
-(void)adjustFrame
{
// We are unable to get textField object while keyboard showing on UIWebView's textField.
if (_textFieldView == nil) return;
// Boolean to know keyboard is showing/hiding
isKeyboardShowing = YES;
// Getting KeyWindow object.
UIWindow *window = [self keyWindow];
// Getting RootViewController.
UIViewController *rootController = [[self keyWindow] topMostController];
// Converting Rectangle according to window bounds.
CGRect textFieldViewRect = [[_textFieldView superview] convertRect:_textFieldView.frame toView:window];
// Getting RootViewRect.
CGRect rootViewRect = [[rootController view] frame];
CGFloat move = 0;
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Calculating move position. Common for both normal and special cases.
switch ([rootController interfaceOrientation])
{
case UIInterfaceOrientationLandscapeLeft:
move = CGRectGetMaxX(textFieldViewRect)-(window.width-kbSize.width);
break;
case UIInterfaceOrientationLandscapeRight:
move = kbSize.width-CGRectGetMinX(textFieldViewRect);
break;
case UIInterfaceOrientationPortrait:
move = CGRectGetMaxY(textFieldViewRect)-(window.height-kbSize.height);
break;
case UIInterfaceOrientationPortraitUpsideDown:
move = kbSize.height-CGRectGetMinY(textFieldViewRect);
break;
default:
break;
}
// Getting it's superScrollView.
UIScrollView *superScrollView = [_textFieldView superScrollView];
//If there was a lastScrollView.
if (lastScrollView)
{
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if (superScrollView == nil)
{
[lastScrollView setContentOffset:startingContentOffset animated:YES];
lastScrollView = nil;
startingContentOffset = CGPointZero;
}
//If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
if (superScrollView != lastScrollView)
{
[lastScrollView setContentOffset:startingContentOffset animated:YES];
lastScrollView = superScrollView;
startingContentOffset = superScrollView.contentOffset;
}
}
//If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
else if(superScrollView)
{
lastScrollView = superScrollView;
startingContentOffset = superScrollView.contentOffset;
}
// Special case for ScrollView.
{
// If we found lastScrollView then setting it's contentOffset to show textField.
if (lastScrollView)
{
//Saving
UIView *lastView = _textFieldView;
UIScrollView *superScrollView = lastScrollView;
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
while (superScrollView)
{
//Getting lastViewRect.
CGRect lastViewRect = [[lastView superview] convertRect:lastView.frame toView:superScrollView];
//Calculating the expected Y offset from move and scrollView's contentOffset.
CGFloat shouldOffsetY = superScrollView.contentOffset.y - MIN(superScrollView.contentOffset.y,-move);
//Rearranging the expected Y offset according to the view.
shouldOffsetY = MIN(shouldOffsetY, lastViewRect.origin.y/*-5*/); //-5 is for good UI.//Commenting -5 Bug ID #69
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-superScrollView.contentOffset.y);
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
superScrollView.contentOffset = CGPointMake(superScrollView.contentOffset.x, shouldOffsetY);
} completion:^(BOOL finished) {
}];
// Getting next lastView & superScrollView.
lastView = superScrollView;
superScrollView = [lastView superScrollView];
}
}
//Going ahead. No else if.
}
//Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen).
{
CGFloat initialMove = move;
CGFloat adjustment = 5;
UIInterfaceOrientation interfaceOrientation;
//If it's iOS8 then we should do calculations according to portrait orientations.
if (IQ_IS_IOS8_OR_GREATER) interfaceOrientation = UIInterfaceOrientationPortrait;
else interfaceOrientation = [rootController interfaceOrientation];
switch (interfaceOrientation)
{
case UIInterfaceOrientationLandscapeLeft:
adjustment += [[UIApplication sharedApplication] statusBarFrame].size.width;
move = MIN(CGRectGetMinX(textFieldViewRect)-adjustment, move);
break;
case UIInterfaceOrientationLandscapeRight:
adjustment += [[UIApplication sharedApplication] statusBarFrame].size.width;
move = MIN(window.width-CGRectGetMaxX(textFieldViewRect)-adjustment, move);
break;
case UIInterfaceOrientationPortrait:
adjustment += [[UIApplication sharedApplication] statusBarFrame].size.height;
move = MIN(CGRectGetMinY(textFieldViewRect)-adjustment, move);
break;
case UIInterfaceOrientationPortraitUpsideDown:
adjustment += [[UIApplication sharedApplication] statusBarFrame].size.height;
move = MIN(window.height-CGRectGetMaxY(textFieldViewRect)-adjustment, move);
break;
default:
break;
}
//If we have permission to adjust the textView, then let's do it on behalf of user.
if (_canAdjustTextView)
{
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
_textFieldView.height = _textFieldView.height-(initialMove-move);
} completion:^(BOOL finished) {
}];
}
}
// Special case for iPad modalPresentationStyle.
if ([[[self keyWindow] topMostController] modalPresentationStyle] == UIModalPresentationFormSheet ||
[[[self keyWindow] topMostController] modalPresentationStyle] == UIModalPresentationPageSheet)
{
// Positive or zero.
if (move>=0)
{
// We should only manipulate y.
rootViewRect.origin.y -= move;
[self setRootViewFrame:rootViewRect];
}
// Negative
else
{
// Calculating disturbed distance
CGFloat disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(topViewBeginRect);
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if(disturbDistance<0)
{
// We should only manipulate y.
rootViewRect.origin.y -= MAX(move, disturbDistance);
[self setRootViewFrame:rootViewRect];
}
}
}
//If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
else
{
// Positive or zero.
if (move>=0)
{
// adjusting rootViewRect
UIInterfaceOrientation interfaceOrientation;
//If it's iOS8 then we should do calculations according to portrait orientations.
if (IQ_IS_IOS8_OR_GREATER) interfaceOrientation = UIInterfaceOrientationPortrait;
else interfaceOrientation = [rootController interfaceOrientation];
switch (interfaceOrientation)
{
case UIInterfaceOrientationLandscapeLeft: rootViewRect.origin.x -= move; break;
case UIInterfaceOrientationLandscapeRight: rootViewRect.origin.x += move; break;
case UIInterfaceOrientationPortrait: rootViewRect.origin.y -= move; break;
case UIInterfaceOrientationPortraitUpsideDown: rootViewRect.origin.y += move; break;
default: break;
}
// Setting adjusted rootViewRect
[self setRootViewFrame:rootViewRect];
}
// Negative
else
{
CGFloat disturbDistance = 0;
// Calculating disturbed distance
UIInterfaceOrientation interfaceOrientation;
//If it's iOS8 then we should do calculations according to portrait orientations.
if (IQ_IS_IOS8_OR_GREATER) interfaceOrientation = UIInterfaceOrientationPortrait;
else interfaceOrientation = [rootController interfaceOrientation];
switch (interfaceOrientation)
{
case UIInterfaceOrientationLandscapeLeft:
disturbDistance = CGRectGetMinX(rootViewRect)-CGRectGetMinX(topViewBeginRect);
break;
case UIInterfaceOrientationLandscapeRight:
disturbDistance = CGRectGetMinX(topViewBeginRect)-CGRectGetMinX(rootViewRect);
break;
case UIInterfaceOrientationPortrait:
disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(topViewBeginRect);
break;
case UIInterfaceOrientationPortraitUpsideDown:
disturbDistance = CGRectGetMinY(topViewBeginRect)-CGRectGetMinY(rootViewRect);
break;
default:
break;
}
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if(disturbDistance<0)
{
// adjusting rootViewRect
UIInterfaceOrientation interfaceOrientation;
//If it's iOS8 then we should do calculations according to portrait orientations.
if (IQ_IS_IOS8_OR_GREATER) interfaceOrientation = UIInterfaceOrientationPortrait;
else interfaceOrientation = [rootController interfaceOrientation];
switch (interfaceOrientation)
{
case UIInterfaceOrientationLandscapeLeft: rootViewRect.origin.x -= MAX(move, disturbDistance); break;
case UIInterfaceOrientationLandscapeRight: rootViewRect.origin.x += MAX(move, disturbDistance); break;
case UIInterfaceOrientationPortrait: rootViewRect.origin.y -= MAX(move, disturbDistance); break;
case UIInterfaceOrientationPortraitUpsideDown: rootViewRect.origin.y += MAX(move, disturbDistance); break;
default: break;
}
// Setting adjusted rootViewRect
[self setRootViewFrame:rootViewRect];
}
}
}
}
#pragma mark - UIKeyboad Notification methods
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
- (void)keyboardWillHide:(NSNotification*)aNotification
{
//If it's not a fake notification generated by [self setEnable:NO].
if (aNotification != nil) kbShowNotification = nil;
//If not enabled then do nothing.
if (_enable == NO) return;
// We are unable to get textField object while keyboard showing on UIWebView's textField.
if (_textFieldView == nil) return;
//If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView)
if (!CGRectEqualToRect(textFieldViewIntialFrame, CGRectZero))
{
//Due to orientation callback we need to set it's original position.
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
_textFieldView.frame = textFieldViewIntialFrame;
} completion:^(BOOL finished) {
}];
}
// Boolean to know keyboard is showing/hiding
isKeyboardShowing = NO;
// Getting keyboard animation duration
CGFloat aDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
if (aDuration!= 0.0f)
{
// Setitng keyboard animation duration
animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
}
//Restoring the contentOffset of the lastScrollView
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
lastScrollView.contentOffset = startingContentOffset;
// TODO: This is temporary solution. Have to implement the save and restore scrollView state
UIScrollView *superscrollView = lastScrollView;
while ((superscrollView = [superscrollView superScrollView]))
{
CGSize contentSize = CGSizeMake(MAX(superscrollView.contentSize.width, superscrollView.width), MAX(superscrollView.contentSize.height, superscrollView.height));
CGFloat minimumY = contentSize.height-superscrollView.height;
if (minimumY<superscrollView.contentOffset.y)
{
superscrollView.contentOffset = CGPointMake(superscrollView.contentOffset.x, minimumY);
}
}
} completion:^(BOOL finished) {
}];
//Reset all values
lastScrollView = nil;
kbSize = CGSizeZero;
startingContentOffset = CGPointZero;
// Setting rootViewController frame to it's original position.
[self setRootViewFrame:topViewBeginRect];
}
/* UIKeyboardWillShowNotification. */
-(void)keyboardWillShow:(NSNotification*)aNotification
{
kbShowNotification = aNotification;
if (_enable == NO) return;
//Due to orientation callback we need to resave it's original frame.
textFieldViewIntialFrame = _enable && _canAdjustTextView ? _textFieldView.frame : CGRectZero;
if (_shouldAdoptDefaultKeyboardAnimation)
{
// Getting keyboard animation.
animationCurve = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
animationCurve = animationCurve<<16;
}
else
{
animationCurve = 0;
}
// Getting keyboard animation duration
CGFloat duration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//Saving animation duration
if (duration != 0.0) animationDuration = duration;
CGSize oldKBSize = kbSize;
// Getting UIKeyboardSize.
kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
// Adding Keyboard distance from textField.
UIInterfaceOrientation interfaceOrientation;
if (IQ_IS_IOS8_OR_GREATER) interfaceOrientation = UIInterfaceOrientationPortrait;
else interfaceOrientation = [[[self keyWindow] topMostController] interfaceOrientation];
switch (interfaceOrientation)
{
case UIInterfaceOrientationLandscapeLeft:
kbSize.width += _keyboardDistanceFromTextField;
break;
case UIInterfaceOrientationLandscapeRight:
kbSize.width += _keyboardDistanceFromTextField;
break;
case UIInterfaceOrientationPortrait:
kbSize.height += _keyboardDistanceFromTextField;
break;
case UIInterfaceOrientationPortraitUpsideDown:
kbSize.height += _keyboardDistanceFromTextField;
break;
default:
break;
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if (!CGSizeEqualToSize(kbSize, oldKBSize))
{
//If it is EventKit textView object then let EventKit to adjust it. (Bug ID: #37)
if ([_textFieldView isEventKitTextView] == NO)
{
[self adjustFrame];
}
}
}
#pragma mark - UITextFieldView Delegate methods
/*! UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
-(void)textFieldViewDidEndEditing:(NSNotification*)notification
{
[_textFieldView.window removeGestureRecognizer:tapGesture];
// We check if there's a valid frame before resetting the textview's frame
if(!CGRectEqualToRect(textFieldViewIntialFrame, CGRectZero)){
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
_textFieldView.frame = textFieldViewIntialFrame;
} completion:^(BOOL finished) {
}];
}
//Setting object to nil
_textFieldView = nil;
}
/*! UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
-(void)textFieldViewDidBeginEditing:(NSNotification*)notification
{
// Getting object
_textFieldView = notification.object;
if (_overrideKeyboardAppearance == YES) [(UITextField*)_textFieldView setKeyboardAppearance:_keyboardAppearance];
// If the manager is not enabled and it can't adjust the textview set the initial frame to CGRectZero
textFieldViewIntialFrame = _enable && _canAdjustTextView ? _textFieldView.frame : CGRectZero;
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if (_enableAutoToolbar)
{
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if ([_textFieldView isKindOfClass:[UITextView class]] && _textFieldView.inputAccessoryView == nil)
{
UIView *view = _textFieldView;
[UIView animateWithDuration:0.00001 delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
[self addToolbarIfRequired];
} completion:^(BOOL finished) {
[view resignFirstResponder];
[view becomeFirstResponder];
}];
}
else
{
[self addToolbarIfRequired];
}
}
if (_enable == NO) return;
[_textFieldView.window addGestureRecognizer:tapGesture];
if (isKeyboardShowing == NO)
{
// keyboard is not showing(At the beginning only). We should save rootViewRect.
UIViewController *rootController = [[self keyWindow] topMostController];
topViewBeginRect = rootController.view.frame;
}
//If it is EventKit textView object then let EventKit to adjust it. (Bug ID: #37)
if ([_textFieldView isEventKitTextView] == NO)
{
// keyboard is already showing. adjust frame.
[self adjustFrame];
}
}
/* UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */
-(void)textFieldViewDidChange:(NSNotification*)notification
{
UITextView *textView = (UITextView *)notification.object;
CGRect line = [textView caretRectForPosition: textView.selectedTextRange.start];
CGFloat overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top);
if ( overflow > 0 )
{
// We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
// Scroll caret to visible area
CGPoint offset = textView.contentOffset;
offset.y += overflow + 7; // leave 7 pixels margin
// Cannot animate with setContentOffset:animated: or caret will not appear
[UIView animateWithDuration:animationDuration delay:0 options:(animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
[textView setContentOffset:offset];
} completion:^(BOOL finished) {
}];
}
}
#pragma mark AutoResign methods
/*! Enabling/disable gesture on touching. */
-(void)setShouldResignOnTouchOutside:(BOOL)shouldResignOnTouchOutside
{
_shouldResignOnTouchOutside = shouldResignOnTouchOutside;
[tapGesture setEnabled:_shouldResignOnTouchOutside];
}
/*! Resigning on tap gesture. */
- (void)tapRecognized:(UITapGestureRecognizer*)gesture
{
if (gesture.state == UIGestureRecognizerStateEnded)
{
[gesture.view endEditing:YES];
}
}
/*! Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return NO;
}
/*! Resigning textField. */
- (void)resignFirstResponder
{
[_textFieldView resignFirstResponder];
}
#pragma mark AutoToolbar methods
/*! return YES. If autoToolbar is enabled. */
-(BOOL)isEnableAutoToolbar
{
return _enableAutoToolbar;
}
/*! Enable/disable autotoolbar. Adding and removing toolbar if required. */
-(void)setEnableAutoToolbar:(BOOL)enableAutoToolbar
{
_enableAutoToolbar = enableAutoToolbar;
if (_enableAutoToolbar == YES)
{
[self addToolbarIfRequired];
}
else
{
[self removeToolbarIfRequired];
}
}
/*! Get all UITextField/UITextView siblings of textFieldView. */
-(NSArray*)responderViews
{
UITableView *tableView = [_textFieldView superTableView];
NSArray *textFields;
//If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
if (tableView)
{
textFields = [tableView deepResponderViews];
}
//Otherwise fetching all the siblings
else
{
textFields = [_textFieldView responderSiblings];
}
//Sorting textFields according to behaviour
switch (_toolbarManageBehaviour)
{
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarBySubviews:
return textFields;
break;
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarByTag:
return [textFields sortedArrayByTag];
break;
}
}
#pragma mark previous/next/done functionality
/*! previousAction. */
-(void)previousAction:(id)segmentedControl
{
if (_shouldPlayInputClicks)
{
[[UIDevice currentDevice] playInputClick];
}
//Getting all responder view's.
NSArray *textFields = [self responderViews];
if ([textFields containsObject:_textFieldView])
{
//Getting index of current textField.
NSUInteger index = [textFields indexOfObject:_textFieldView];
//If it is not first textField. then it's previous object becomeFirstResponder.
if (index > 0) [[textFields objectAtIndex:index-1] becomeFirstResponder];
}
}
/*! nextAction. */
-(void)nextAction:(id)segmentedControl
{
if (_shouldPlayInputClicks)
{
[[UIDevice currentDevice] playInputClick];
}
//Getting all responder view's.
NSArray *textFields = [self responderViews];
if ([textFields containsObject:_textFieldView])
{
//Getting index of current textField.
NSUInteger index = [textFields indexOfObject:_textFieldView];
//If it is not last textField. then it's next object becomeFirstResponder.
if (index < textFields.count-1) [[textFields objectAtIndex:index+1] becomeFirstResponder];
}
}
/*! doneAction. Resigning current textField. */
-(void)doneAction:(IQBarButtonItem*)barButton
{
if (_shouldPlayInputClicks)
{
[[UIDevice currentDevice] playInputClick];
}
[self resignFirstResponder];
}
/*! Add toolbar if it is required to add on textFields and it's siblings. */
-(void)addToolbarIfRequired
{
// Getting all the sibling textFields.
NSArray *siblings = [self responderViews];
// If only one object is found, then adding only Done button.
if (siblings.count==1)
{
UIView *textField = [siblings firstObject];
if (![textField inputAccessoryView] || [[textField inputAccessoryView] tag] != kIQDoneButtonToolbarTag)
{
[textField addDoneOnKeyboardWithTarget:self action:@selector(doneAction:) shouldShowPlaceholder:_shouldShowTextFieldPlaceholder];
//Setting toolbar tintColor
if (_shouldToolbarUsesTextFieldTintColor && [textField respondsToSelector:@selector(tintColor)])
[textField.inputAccessoryView setTintColor:[textField tintColor]];
//Setting toolbar title font.
if (_shouldShowTextFieldPlaceholder && _placeholderFont && [_placeholderFont isKindOfClass:[UIFont class]])
[(IQToolbar*)[textField inputAccessoryView] setTitleFont:_placeholderFont];
}
}
else if(siblings.count)
{
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for (UITextField *textField in siblings)
{
if (![textField inputAccessoryView] || [[textField inputAccessoryView] tag] != kIQPreviousNextButtonToolbarTag)
{
[textField addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(previousAction:) nextAction:@selector(nextAction:) doneAction:@selector(doneAction:) shouldShowPlaceholder:_shouldShowTextFieldPlaceholder];
//Setting toolbar tintColor
if (_shouldToolbarUsesTextFieldTintColor && [textField respondsToSelector:@selector(tintColor)])
[textField.inputAccessoryView setTintColor:[textField tintColor]];
//Setting toolbar title font.
if (_shouldShowTextFieldPlaceholder && _placeholderFont && [_placeholderFont isKindOfClass:[UIFont class]])
[(IQToolbar*)[textField inputAccessoryView] setTitleFont:_placeholderFont];
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime.
// If firstTextField, then previous should not be enabled.
if ([siblings objectAtIndex:0] == textField)
{
[textField setEnablePrevious:NO next:YES];
}
// If lastTextField then next should not be enaled.