IQKeyboardManager.m 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. //
  2. // IQKeyboardManager.m
  3. // https://github.com/hackiftekhar/IQKeyboardManager
  4. // Copyright (c) 2013-16 Iftekhar Qurashi.
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. #import <QuartzCore/QuartzCore.h>
  24. #import <UIKit/UIKit.h>
  25. #import <objc/runtime.h>
  26. #import "IQKeyboardManager.h"
  27. #import "IQUIView+Hierarchy.h"
  28. #import "IQUIView+IQKeyboardToolbar.h"
  29. #import "IQNSArray+Sort.h"
  30. #import "IQKeyboardManagerConstantsInternal.h"
  31. #import "IQUIScrollView+Additions.h"
  32. #import "IQUITextFieldView+Additions.h"
  33. #import "IQUIViewController+Additions.h"
  34. #import "IQPreviousNextView.h"
  35. NSInteger const kIQDoneButtonToolbarTag = -1002;
  36. NSInteger const kIQPreviousNextButtonToolbarTag = -1005;
  37. #define kIQCGPointInvalid CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)
  38. typedef void (^SizeBlock)(CGSize size);
  39. @interface IQKeyboardManager()<UIGestureRecognizerDelegate>
  40. /*******************************************/
  41. /** used to adjust contentInset of UITextView. */
  42. @property(nonatomic, assign) UIEdgeInsets startingTextViewContentInsets;
  43. /** used to adjust scrollIndicatorInsets of UITextView. */
  44. @property(nonatomic, assign) UIEdgeInsets startingTextViewScrollIndicatorInsets;
  45. /** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
  46. @property(nonatomic, assign) BOOL isTextViewContentInsetChanged;
  47. /*******************************************/
  48. /** To save UITextField/UITextView object voa textField/textView notifications. */
  49. @property(nullable, nonatomic, weak) UIView *textFieldView;
  50. /** To save rootViewController.view.frame.origin. */
  51. @property(nonatomic, assign) CGPoint topViewBeginOrigin;
  52. /** To save rootViewController */
  53. @property(nullable, nonatomic, weak) UIViewController *rootViewController;
  54. /** To overcome with popGestureRecognizer issue Bug ID: #1361 */
  55. @property(nullable, nonatomic, weak) UIViewController *rootViewControllerWhilePopGestureRecognizerActive;
  56. @property(nonatomic, assign) CGPoint topViewBeginOriginWhilePopGestureRecognizerActive;
  57. /** To know if we have any pending request to adjust view position. */
  58. @property(nonatomic, assign) BOOL hasPendingAdjustRequest;
  59. /*******************************************/
  60. /** Variable to save lastScrollView that was scrolled. */
  61. @property(nullable, nonatomic, weak) UIScrollView *lastScrollView;
  62. /** LastScrollView's initial contentInsets. */
  63. @property(nonatomic, assign) UIEdgeInsets startingContentInsets;
  64. /** LastScrollView's initial scrollIndicatorInsets. */
  65. @property(nonatomic, assign) UIEdgeInsets startingScrollIndicatorInsets;
  66. /** LastScrollView's initial contentOffset. */
  67. @property(nonatomic, assign) CGPoint startingContentOffset;
  68. /*******************************************/
  69. /** To save keyboard animation duration. */
  70. @property(nonatomic, assign) CGFloat animationDuration;
  71. /** To mimic the keyboard animation */
  72. @property(nonatomic, assign) NSInteger animationCurve;
  73. /*******************************************/
  74. /** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */
  75. @property(nonnull, nonatomic, strong, readwrite) UITapGestureRecognizer *resignFirstResponderGesture;
  76. /**
  77. moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
  78. */
  79. @property(nonatomic, assign, readwrite) CGFloat movedDistance;
  80. /*******************************************/
  81. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *disabledDistanceHandlingClasses;
  82. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *enabledDistanceHandlingClasses;
  83. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *disabledToolbarClasses;
  84. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *enabledToolbarClasses;
  85. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *toolbarPreviousNextAllowedClasses;
  86. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *disabledTouchResignedClasses;
  87. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *enabledTouchResignedClasses;
  88. @property(nonatomic, strong, nonnull, readwrite) NSMutableSet<Class> *touchResignedGestureIgnoreClasses;
  89. /*******************************************/
  90. @end
  91. @implementation IQKeyboardManager
  92. {
  93. @package
  94. /*******************************************/
  95. /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
  96. NSNotification *_kbShowNotification;
  97. /** To save keyboard size. */
  98. CGRect _kbFrame;
  99. CGSize _keyboardLastNotifySize;
  100. NSMutableDictionary<id<NSCopying>, SizeBlock>* _keyboardSizeObservers;
  101. /*******************************************/
  102. }
  103. //UIKeyboard handling
  104. @synthesize enable = _enable;
  105. @synthesize keyboardDistanceFromTextField = _keyboardDistanceFromTextField;
  106. //Keyboard Appearance handling
  107. @synthesize overrideKeyboardAppearance = _overrideKeyboardAppearance;
  108. @synthesize keyboardAppearance = _keyboardAppearance;
  109. //IQToolbar handling
  110. @synthesize enableAutoToolbar = _enableAutoToolbar;
  111. @synthesize toolbarManageBehaviour = _toolbarManageBehaviour;
  112. @synthesize shouldToolbarUsesTextFieldTintColor = _shouldToolbarUsesTextFieldTintColor;
  113. @synthesize toolbarTintColor = _toolbarTintColor;
  114. @synthesize toolbarBarTintColor = _toolbarBarTintColor;
  115. @synthesize shouldShowToolbarPlaceholder = _shouldShowToolbarPlaceholder;
  116. @synthesize placeholderFont = _placeholderFont;
  117. @synthesize placeholderColor = _placeholderColor;
  118. @synthesize placeholderButtonColor = _placeholderButtonColor;
  119. //Resign handling
  120. @synthesize shouldResignOnTouchOutside = _shouldResignOnTouchOutside;
  121. @synthesize resignFirstResponderGesture = _resignFirstResponderGesture;
  122. //Sound handling
  123. @synthesize shouldPlayInputClicks = _shouldPlayInputClicks;
  124. //Animation handling
  125. @synthesize layoutIfNeededOnUpdate = _layoutIfNeededOnUpdate;
  126. #pragma mark - Initializing functions
  127. /**
  128. Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code)
  129. @Note: If you want to disable `+ (void)load` method, you can add build setting in configurations. Like that:
  130. `{ 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) IQ_KEYBOARD_MANAGER_LOAD_METHOD_DISABLE=1' }`
  131. */
  132. #if !IQ_KEYBOARD_MANAGER_LOAD_METHOD_DISABLE
  133. +(void)load
  134. {
  135. //Enabling IQKeyboardManager. Loading asynchronous on main thread
  136. [self performSelectorOnMainThread:@selector(sharedManager) withObject:nil waitUntilDone:NO];
  137. }
  138. #endif
  139. /* Singleton Object Initialization. */
  140. -(instancetype)init
  141. {
  142. if (self = [super init])
  143. {
  144. __weak __typeof__(self) weakSelf = self;
  145. static dispatch_once_t onceToken;
  146. dispatch_once(&onceToken, ^{
  147. __strong __typeof__(self) strongSelf = weakSelf;
  148. [strongSelf registerAllNotifications];
  149. //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
  150. strongSelf.resignFirstResponderGesture = [[UITapGestureRecognizer alloc] initWithTarget:strongSelf action:@selector(tapRecognized:)];
  151. strongSelf.resignFirstResponderGesture.cancelsTouchesInView = NO;
  152. [strongSelf.resignFirstResponderGesture setDelegate:strongSelf];
  153. strongSelf.resignFirstResponderGesture.enabled = strongSelf.shouldResignOnTouchOutside;
  154. strongSelf.topViewBeginOrigin = kIQCGPointInvalid;
  155. strongSelf.topViewBeginOriginWhilePopGestureRecognizerActive = kIQCGPointInvalid;
  156. //Setting it's initial values
  157. strongSelf.animationDuration = 0.25;
  158. strongSelf.animationCurve = UIViewAnimationCurveEaseInOut;
  159. [strongSelf setEnable:YES];
  160. [strongSelf setKeyboardDistanceFromTextField:10.0];
  161. [strongSelf setShouldPlayInputClicks:YES];
  162. [strongSelf setShouldResignOnTouchOutside:NO];
  163. [strongSelf setOverrideKeyboardAppearance:NO];
  164. [strongSelf setKeyboardAppearance:UIKeyboardAppearanceDefault];
  165. [strongSelf setEnableAutoToolbar:YES];
  166. [strongSelf setShouldShowToolbarPlaceholder:YES];
  167. [strongSelf setToolbarManageBehaviour:IQAutoToolbarBySubviews];
  168. [strongSelf setLayoutIfNeededOnUpdate:NO];
  169. [strongSelf setShouldToolbarUsesTextFieldTintColor:NO];
  170. //Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550)
  171. {
  172. //If you experience exception breakpoint issue at below line then try these solutions https://stackoverflow.com/questions/27375640/all-exception-break-point-is-stopping-for-no-reason-on-simulator
  173. UITextField *view = [[UITextField alloc] init];
  174. [view addDoneOnKeyboardWithTarget:nil action:nil];
  175. [view addPreviousNextDoneOnKeyboardWithTarget:nil previousAction:nil nextAction:nil doneAction:nil];
  176. }
  177. strongSelf->_keyboardSizeObservers = [[NSMutableDictionary alloc] init];
  178. //Initializing disabled classes Set.
  179. strongSelf.disabledDistanceHandlingClasses = [[NSMutableSet alloc] initWithObjects:[UITableViewController class],[UIAlertController class], nil];
  180. strongSelf.enabledDistanceHandlingClasses = [[NSMutableSet alloc] init];
  181. strongSelf.disabledToolbarClasses = [[NSMutableSet alloc] initWithObjects:[UIAlertController class], nil];
  182. strongSelf.enabledToolbarClasses = [[NSMutableSet alloc] init];
  183. strongSelf.toolbarPreviousNextAllowedClasses = [[NSMutableSet alloc] initWithObjects:[UITableView class],[UICollectionView class],[IQPreviousNextView class], nil];
  184. strongSelf.disabledTouchResignedClasses = [[NSMutableSet alloc] initWithObjects:[UIAlertController class], nil];
  185. strongSelf.enabledTouchResignedClasses = [[NSMutableSet alloc] init];
  186. strongSelf.touchResignedGestureIgnoreClasses = [[NSMutableSet alloc] initWithObjects:[UIControl class],[UINavigationBar class], nil];
  187. });
  188. }
  189. return self;
  190. }
  191. /* Automatically called from the `+(void)load` method. */
  192. + (IQKeyboardManager*)sharedManager
  193. {
  194. //Singleton instance
  195. static IQKeyboardManager *kbManager;
  196. static dispatch_once_t onceToken;
  197. dispatch_once(&onceToken, ^{
  198. kbManager = [[self alloc] init];
  199. });
  200. return kbManager;
  201. }
  202. #pragma mark - Dealloc
  203. -(void)dealloc
  204. {
  205. // Disable the keyboard manager.
  206. [self setEnable:NO];
  207. //Removing notification observers on dealloc.
  208. [[NSNotificationCenter defaultCenter] removeObserver:self];
  209. }
  210. #pragma mark - Property functions
  211. -(void)setEnable:(BOOL)enable
  212. {
  213. // If not enabled, enable it.
  214. if (enable == YES &&
  215. _enable == NO)
  216. {
  217. //Setting YES to _enable.
  218. _enable = enable;
  219. //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
  220. if (_kbShowNotification) [self keyboardWillShow:_kbShowNotification];
  221. [self showLog:@"Enabled"];
  222. }
  223. //If not disable, desable it.
  224. else if (enable == NO &&
  225. _enable == YES)
  226. {
  227. //Sending a fake notification for keyboardWillHide to retain view's original position.
  228. [self keyboardWillHide:nil];
  229. //Setting NO to _enable.
  230. _enable = enable;
  231. [self showLog:@"Disabled"];
  232. }
  233. //If already disabled.
  234. else if (enable == NO &&
  235. _enable == NO)
  236. {
  237. [self showLog:@"Already Disabled"];
  238. }
  239. //If already enabled.
  240. else if (enable == YES &&
  241. _enable == YES)
  242. {
  243. [self showLog:@"Already Enabled"];
  244. }
  245. }
  246. -(BOOL)privateIsEnabled
  247. {
  248. BOOL enable = _enable;
  249. IQEnableMode enableMode = _textFieldView.enableMode;
  250. if (enableMode == IQEnableModeEnabled)
  251. {
  252. enable = YES;
  253. }
  254. else if (enableMode == IQEnableModeDisabled)
  255. {
  256. enable = NO;
  257. }
  258. else
  259. {
  260. __strong __typeof__(UIView) *strongTextFieldView = _textFieldView;
  261. UIViewController *textFieldViewController = [strongTextFieldView viewContainingController];
  262. if (textFieldViewController)
  263. {
  264. //If it is searchBar textField embedded in Navigation Bar
  265. if ([strongTextFieldView textFieldSearchBar] != nil && [textFieldViewController isKindOfClass:[UINavigationController class]]) {
  266. UINavigationController *navController = (UINavigationController*)textFieldViewController;
  267. if (navController.topViewController) {
  268. textFieldViewController = navController.topViewController;
  269. }
  270. }
  271. if (enable == NO)
  272. {
  273. //If viewController is kind of enable viewController class, then assuming it's enabled.
  274. for (Class enabledClass in _enabledDistanceHandlingClasses)
  275. {
  276. if ([textFieldViewController isKindOfClass:enabledClass])
  277. {
  278. enable = YES;
  279. break;
  280. }
  281. }
  282. }
  283. if (enable)
  284. {
  285. //If viewController is kind of disable viewController class, then assuming it's disable.
  286. for (Class disabledClass in _disabledDistanceHandlingClasses)
  287. {
  288. if ([textFieldViewController isKindOfClass:disabledClass])
  289. {
  290. enable = NO;
  291. break;
  292. }
  293. }
  294. //Special Controllers
  295. if (enable == YES)
  296. {
  297. NSString *classNameString = NSStringFromClass([textFieldViewController class]);
  298. //_UIAlertControllerTextFieldViewController
  299. if ([classNameString containsString:@"UIAlertController"] && [classNameString hasSuffix:@"TextFieldViewController"])
  300. {
  301. enable = NO;
  302. }
  303. }
  304. }
  305. }
  306. }
  307. return enable;
  308. }
  309. // Setting keyboard distance from text field.
  310. -(void)setKeyboardDistanceFromTextField:(CGFloat)keyboardDistanceFromTextField
  311. {
  312. //Can't be less than zero. Minimum is zero.
  313. _keyboardDistanceFromTextField = MAX(keyboardDistanceFromTextField, 0);
  314. [self showLog:[NSString stringWithFormat:@"keyboardDistanceFromTextField: %.2f",_keyboardDistanceFromTextField]];
  315. }
  316. /** Enabling/disable gesture on touching. */
  317. -(void)setShouldResignOnTouchOutside:(BOOL)shouldResignOnTouchOutside
  318. {
  319. [self showLog:[NSString stringWithFormat:@"shouldResignOnTouchOutside: %@",shouldResignOnTouchOutside?@"Yes":@"No"]];
  320. _shouldResignOnTouchOutside = shouldResignOnTouchOutside;
  321. //Enable/Disable gesture recognizer (Enhancement ID: #14)
  322. [_resignFirstResponderGesture setEnabled:[self privateShouldResignOnTouchOutside]];
  323. }
  324. -(BOOL)privateShouldResignOnTouchOutside
  325. {
  326. BOOL shouldResignOnTouchOutside = _shouldResignOnTouchOutside;
  327. __strong __typeof__(UIView) *strongTextFieldView = _textFieldView;
  328. IQEnableMode enableMode = strongTextFieldView.shouldResignOnTouchOutsideMode;
  329. if (enableMode == IQEnableModeEnabled)
  330. {
  331. shouldResignOnTouchOutside = YES;
  332. }
  333. else if (enableMode == IQEnableModeDisabled)
  334. {
  335. shouldResignOnTouchOutside = NO;
  336. }
  337. else
  338. {
  339. UIViewController *textFieldViewController = [strongTextFieldView viewContainingController];
  340. if (textFieldViewController)
  341. {
  342. //If it is searchBar textField embedded in Navigation Bar
  343. if ([strongTextFieldView textFieldSearchBar] != nil && [textFieldViewController isKindOfClass:[UINavigationController class]]) {
  344. UINavigationController *navController = (UINavigationController*)textFieldViewController;
  345. if (navController.topViewController) {
  346. textFieldViewController = navController.topViewController;
  347. }
  348. }
  349. if (shouldResignOnTouchOutside == NO)
  350. {
  351. //If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
  352. for (Class enabledClass in _enabledTouchResignedClasses)
  353. {
  354. if ([textFieldViewController isKindOfClass:enabledClass])
  355. {
  356. shouldResignOnTouchOutside = YES;
  357. break;
  358. }
  359. }
  360. }
  361. if (shouldResignOnTouchOutside)
  362. {
  363. //If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
  364. for (Class disabledClass in _disabledTouchResignedClasses)
  365. {
  366. if ([textFieldViewController isKindOfClass:disabledClass])
  367. {
  368. shouldResignOnTouchOutside = NO;
  369. break;
  370. }
  371. }
  372. //Special Controllers
  373. if (shouldResignOnTouchOutside == YES)
  374. {
  375. NSString *classNameString = NSStringFromClass([textFieldViewController class]);
  376. //_UIAlertControllerTextFieldViewController
  377. if ([classNameString containsString:@"UIAlertController"] && [classNameString hasSuffix:@"TextFieldViewController"])
  378. {
  379. shouldResignOnTouchOutside = NO;
  380. }
  381. }
  382. }
  383. }
  384. }
  385. return shouldResignOnTouchOutside;
  386. }
  387. /** Setter of movedDistance property. */
  388. -(void)setMovedDistance:(CGFloat)movedDistance
  389. {
  390. _movedDistance = movedDistance;
  391. if (self.movedDistanceChanged != nil) {
  392. self.movedDistanceChanged(movedDistance);
  393. }
  394. }
  395. /** Enable/disable autotoolbar. Adding and removing toolbar if required. */
  396. -(void)setEnableAutoToolbar:(BOOL)enableAutoToolbar
  397. {
  398. _enableAutoToolbar = enableAutoToolbar;
  399. [self showLog:[NSString stringWithFormat:@"enableAutoToolbar: %@",enableAutoToolbar?@"Yes":@"No"]];
  400. //If enabled then adding toolbar.
  401. if ([self privateIsEnableAutoToolbar] == YES)
  402. {
  403. [self addToolbarIfRequired];
  404. }
  405. //Else removing toolbar.
  406. else
  407. {
  408. [self removeToolbarIfRequired];
  409. }
  410. }
  411. -(BOOL)privateIsEnableAutoToolbar
  412. {
  413. BOOL enableAutoToolbar = _enableAutoToolbar;
  414. __strong __typeof__(UIView) *strongTextFieldView = _textFieldView;
  415. UIViewController *textFieldViewController = [strongTextFieldView viewContainingController];
  416. if (textFieldViewController)
  417. {
  418. //If it is searchBar textField embedded in Navigation Bar
  419. if ([strongTextFieldView textFieldSearchBar] != nil && [textFieldViewController isKindOfClass:[UINavigationController class]]) {
  420. UINavigationController *navController = (UINavigationController*)textFieldViewController;
  421. if (navController.topViewController) {
  422. textFieldViewController = navController.topViewController;
  423. }
  424. }
  425. if (enableAutoToolbar == NO)
  426. {
  427. //If found any toolbar enabled classes then return.
  428. for (Class enabledToolbarClass in _enabledToolbarClasses)
  429. {
  430. if ([textFieldViewController isKindOfClass:enabledToolbarClass])
  431. {
  432. enableAutoToolbar = YES;
  433. break;
  434. }
  435. }
  436. }
  437. if (enableAutoToolbar)
  438. {
  439. //If found any toolbar disabled classes then return.
  440. for (Class disabledToolbarClass in _disabledToolbarClasses)
  441. {
  442. if ([textFieldViewController isKindOfClass:disabledToolbarClass])
  443. {
  444. enableAutoToolbar = NO;
  445. break;
  446. }
  447. }
  448. //Special Controllers
  449. if (enableAutoToolbar == YES)
  450. {
  451. NSString *classNameString = NSStringFromClass([textFieldViewController class]);
  452. //_UIAlertControllerTextFieldViewController
  453. if ([classNameString containsString:@"UIAlertController"] && [classNameString hasSuffix:@"TextFieldViewController"])
  454. {
  455. enableAutoToolbar = NO;
  456. }
  457. }
  458. }
  459. }
  460. return enableAutoToolbar;
  461. }
  462. #pragma mark - Private Methods
  463. /** Getting keyWindow. */
  464. -(UIWindow *)keyWindow
  465. {
  466. UIView *textFieldView = _textFieldView;
  467. if (textFieldView.window)
  468. {
  469. return textFieldView.window;
  470. }
  471. else
  472. {
  473. static __weak UIWindow *cachedKeyWindow = nil;
  474. /* (Bug ID: #23, #25, #73) */
  475. UIWindow *originalKeyWindow = nil;
  476. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  477. if (@available(iOS 13.0, *)) {
  478. NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
  479. for (UIScene *scene in connectedScenes) {
  480. if (scene.activationState == UISceneActivationStateForegroundActive && [scene isKindOfClass:[UIWindowScene class]]) {
  481. UIWindowScene *windowScene = (UIWindowScene *)scene;
  482. for (UIWindow *window in windowScene.windows) {
  483. if (window.isKeyWindow) {
  484. originalKeyWindow = window;
  485. break;
  486. }
  487. }
  488. }
  489. }
  490. } else
  491. #endif
  492. {
  493. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  494. originalKeyWindow = [UIApplication sharedApplication].keyWindow;
  495. #endif
  496. }
  497. //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
  498. if (originalKeyWindow)
  499. {
  500. cachedKeyWindow = originalKeyWindow;
  501. }
  502. __strong UIWindow *strongCachedKeyWindow = cachedKeyWindow;
  503. return strongCachedKeyWindow;
  504. }
  505. }
  506. -(void)optimizedAdjustPosition
  507. {
  508. if (_hasPendingAdjustRequest == NO)
  509. {
  510. _hasPendingAdjustRequest = YES;
  511. __weak __typeof__(self) weakSelf = self;
  512. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  513. __strong __typeof__(self) strongSelf = weakSelf;
  514. [strongSelf adjustPosition];
  515. strongSelf.hasPendingAdjustRequest = NO;
  516. }];
  517. }
  518. }
  519. /* Adjusting RootViewController's frame according to interface orientation. */
  520. -(void)adjustPosition
  521. {
  522. UIView *textFieldView = _textFieldView;
  523. // Getting RootViewController. (Bug ID: #1, #4)
  524. UIViewController *rootController = _rootViewController;
  525. // Getting KeyWindow object.
  526. UIWindow *keyWindow = [self keyWindow];
  527. // We are unable to get textField object while keyboard showing on WKWebView's textField. (Bug ID: #11)
  528. if (_hasPendingAdjustRequest == NO ||
  529. textFieldView == nil ||
  530. rootController == nil ||
  531. keyWindow == nil)
  532. return;
  533. CFTimeInterval startTime = CACurrentMediaTime();
  534. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  535. // Converting Rectangle according to window bounds.
  536. CGRect textFieldViewRectInWindow = [[textFieldView superview] convertRect:textFieldView.frame toView:keyWindow];
  537. CGRect textFieldViewRectInRootSuperview = [[textFieldView superview] convertRect:textFieldView.frame toView:rootController.view.superview];
  538. // Getting RootView origin.
  539. CGPoint rootViewOrigin = rootController.view.frame.origin;
  540. //Maintain keyboardDistanceFromTextField
  541. CGFloat specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField;
  542. {
  543. UISearchBar *searchBar = textFieldView.textFieldSearchBar;
  544. if (searchBar)
  545. {
  546. specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField;
  547. }
  548. }
  549. CGFloat keyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance)?_keyboardDistanceFromTextField:specialKeyboardDistanceFromTextField;
  550. CGSize kbSize;
  551. {
  552. CGRect kbFrame = _kbFrame;
  553. kbFrame.origin.y -= keyboardDistanceFromTextField;
  554. kbFrame.size.height += keyboardDistanceFromTextField;
  555. //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) (Bug ID: #1506)
  556. CGRect intersectRect = CGRectIntersection(kbFrame, keyWindow.frame);
  557. if (CGRectIsNull(intersectRect))
  558. {
  559. kbSize = CGSizeMake(kbFrame.size.width, 0);
  560. }
  561. else
  562. {
  563. kbSize = intersectRect.size;
  564. }
  565. }
  566. CGFloat navigationBarAreaHeight = 0;
  567. if (rootController.navigationController != nil) {
  568. navigationBarAreaHeight = CGRectGetMaxY(rootController.navigationController.navigationBar.frame);
  569. } else {
  570. CGFloat statusBarHeight = 0;
  571. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  572. if (@available(iOS 13.0, *)) {
  573. statusBarHeight = [self keyWindow].windowScene.statusBarManager.statusBarFrame.size.height;
  574. } else
  575. #endif
  576. {
  577. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  578. statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
  579. #endif
  580. }
  581. navigationBarAreaHeight = statusBarHeight;
  582. }
  583. CGFloat layoutAreaHeight = rootController.view.layoutMargins.top;
  584. CGFloat topLayoutGuide = MAX(navigationBarAreaHeight, layoutAreaHeight) + 5;
  585. CGFloat bottomLayoutGuide = ([textFieldView respondsToSelector:@selector(isEditable)] && [textFieldView isKindOfClass:[UIScrollView class]]) ? 0 : rootController.view.layoutMargins.bottom; //Validation of textView for case where there is a tab bar at the bottom or running on iPhone X and textView is at the bottom.
  586. // +Move positive = textField is hidden.
  587. // -Move negative = textField is showing.
  588. // Calculating move position. Common for both normal and special cases.
  589. CGFloat move = MIN(CGRectGetMinY(textFieldViewRectInRootSuperview)-topLayoutGuide, CGRectGetMaxY(textFieldViewRectInWindow)-(CGRectGetHeight(keyWindow.frame)-kbSize.height)+bottomLayoutGuide);
  590. [self showLog:[NSString stringWithFormat:@"Need to move: %.2f",move]];
  591. UIScrollView *superScrollView = nil;
  592. UIScrollView *superView = (UIScrollView*)[textFieldView superviewOfClassType:[UIScrollView class]];
  593. //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
  594. while (superView)
  595. {
  596. if (superView.isScrollEnabled && superView.shouldIgnoreScrollingAdjustment == NO)
  597. {
  598. superScrollView = superView;
  599. break;
  600. }
  601. else
  602. {
  603. // Getting it's superScrollView. // (Enhancement ID: #21, #24)
  604. superView = (UIScrollView*)[superView superviewOfClassType:[UIScrollView class]];
  605. }
  606. }
  607. __strong __typeof__(UIScrollView) *strongLastScrollView = _lastScrollView;
  608. //If there was a lastScrollView. // (Bug ID: #34)
  609. if (strongLastScrollView)
  610. {
  611. //If we can't find current superScrollView, then setting lastScrollView to it's original form.
  612. if (superScrollView == nil)
  613. {
  614. if (UIEdgeInsetsEqualToEdgeInsets(strongLastScrollView.contentInset, _startingContentInsets) == NO)
  615. {
  616. [self showLog:[NSString stringWithFormat:@"Restoring ScrollView contentInset to : %@",NSStringFromUIEdgeInsets(_startingContentInsets)]];
  617. __weak __typeof__(self) weakSelf = self;
  618. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  619. __strong __typeof__(self) strongSelf = weakSelf;
  620. [strongLastScrollView setContentInset:strongSelf.startingContentInsets];
  621. strongLastScrollView.scrollIndicatorInsets = strongSelf.startingScrollIndicatorInsets;
  622. } completion:NULL];
  623. }
  624. if (strongLastScrollView.shouldRestoreScrollViewContentOffset && CGPointEqualToPoint(strongLastScrollView.contentOffset, _startingContentOffset) == NO)
  625. {
  626. [self showLog:[NSString stringWithFormat:@"Restoring ScrollView contentOffset to : %@",NSStringFromCGPoint(_startingContentOffset)]];
  627. BOOL animatedContentOffset = ([textFieldView superviewOfClassType:[UIStackView class] belowView:strongLastScrollView] != nil); // (Bug ID: #1365, #1508, #1541)
  628. if (animatedContentOffset) {
  629. [strongLastScrollView setContentOffset:_startingContentOffset animated:UIView.areAnimationsEnabled];
  630. } else {
  631. strongLastScrollView.contentOffset = _startingContentOffset;
  632. }
  633. }
  634. _startingContentInsets = UIEdgeInsetsZero;
  635. _startingScrollIndicatorInsets = UIEdgeInsetsZero;
  636. _startingContentOffset = CGPointZero;
  637. _lastScrollView = nil;
  638. strongLastScrollView = _lastScrollView;
  639. }
  640. //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
  641. else if (superScrollView != strongLastScrollView)
  642. {
  643. if (UIEdgeInsetsEqualToEdgeInsets(strongLastScrollView.contentInset, _startingContentInsets) == NO)
  644. {
  645. [self showLog:[NSString stringWithFormat:@"Restoring ScrollView contentInset to : %@",NSStringFromUIEdgeInsets(_startingContentInsets)]];
  646. __weak __typeof__(self) weakSelf = self;
  647. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  648. __strong __typeof__(self) strongSelf = weakSelf;
  649. [strongLastScrollView setContentInset:strongSelf.startingContentInsets];
  650. strongLastScrollView.scrollIndicatorInsets = strongSelf.startingScrollIndicatorInsets;
  651. } completion:NULL];
  652. }
  653. if (strongLastScrollView.shouldRestoreScrollViewContentOffset && CGPointEqualToPoint(strongLastScrollView.contentOffset, _startingContentOffset) == NO)
  654. {
  655. [self showLog:[NSString stringWithFormat:@"Restoring ScrollView contentOffset to : %@",NSStringFromCGPoint(_startingContentOffset)]];
  656. BOOL animatedContentOffset = ([textFieldView superviewOfClassType:[UIStackView class] belowView:strongLastScrollView] != nil); // (Bug ID: #1365, #1508, #1541)
  657. if (animatedContentOffset) {
  658. [strongLastScrollView setContentOffset:_startingContentOffset animated:UIView.areAnimationsEnabled];
  659. } else {
  660. strongLastScrollView.contentOffset = _startingContentOffset;
  661. }
  662. }
  663. _lastScrollView = superScrollView;
  664. strongLastScrollView = _lastScrollView;
  665. _startingContentInsets = superScrollView.contentInset;
  666. _startingContentOffset = superScrollView.contentOffset;
  667. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  668. if (@available(iOS 11.1, *)) {
  669. _startingScrollIndicatorInsets = superScrollView.verticalScrollIndicatorInsets;
  670. } else
  671. #endif
  672. {
  673. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  674. _startingScrollIndicatorInsets = superScrollView.scrollIndicatorInsets;
  675. #endif
  676. }
  677. [self showLog:[NSString stringWithFormat:@"Saving New contentInset: %@ and contentOffset : %@",NSStringFromUIEdgeInsets(_startingContentInsets),NSStringFromCGPoint(_startingContentOffset)]];
  678. }
  679. //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing
  680. }
  681. //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
  682. else if(superScrollView)
  683. {
  684. _lastScrollView = superScrollView;
  685. strongLastScrollView = _lastScrollView;
  686. _startingContentInsets = superScrollView.contentInset;
  687. _startingContentOffset = superScrollView.contentOffset;
  688. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  689. if (@available(iOS 11.1, *)) {
  690. _startingScrollIndicatorInsets = superScrollView.verticalScrollIndicatorInsets;
  691. } else
  692. #endif
  693. {
  694. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  695. _startingScrollIndicatorInsets = superScrollView.scrollIndicatorInsets;
  696. #endif
  697. }
  698. [self showLog:[NSString stringWithFormat:@"Saving contentInset: %@ and contentOffset : %@",NSStringFromUIEdgeInsets(_startingContentInsets),NSStringFromCGPoint(_startingContentOffset)]];
  699. }
  700. // Special case for ScrollView.
  701. {
  702. // If we found lastScrollView then setting it's contentOffset to show textField.
  703. if (strongLastScrollView)
  704. {
  705. //Saving
  706. UIView *lastView = textFieldView;
  707. superScrollView = strongLastScrollView;
  708. //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
  709. while (superScrollView)
  710. {
  711. BOOL shouldContinue = NO;
  712. if (move > 0)
  713. {
  714. shouldContinue = move > (-superScrollView.contentOffset.y-superScrollView.contentInset.top);
  715. }
  716. else
  717. {
  718. //Special treatment for UITableView due to their cell reusing logic
  719. if ([superScrollView isKindOfClass:[UITableView class]])
  720. {
  721. shouldContinue = superScrollView.contentOffset.y>0;
  722. UITableView *tableView = (UITableView*)superScrollView;
  723. UITableViewCell *tableCell = nil;
  724. NSIndexPath *indexPath = nil;
  725. NSIndexPath *previousIndexPath = nil;
  726. if (shouldContinue &&
  727. (tableCell = (UITableViewCell*)[textFieldView superviewOfClassType:[UITableViewCell class]]) &&
  728. (indexPath = [tableView indexPathForCell:tableCell]) &&
  729. (previousIndexPath = [tableView previousIndexPathOfIndexPath:indexPath]))
  730. {
  731. CGRect previousCellRect = [tableView rectForRowAtIndexPath:previousIndexPath];
  732. if (CGRectIsEmpty(previousCellRect) == NO)
  733. {
  734. CGRect previousCellRectInRootSuperview = [tableView convertRect:previousCellRect toView:rootController.view.superview];
  735. move = MIN(0, CGRectGetMaxY(previousCellRectInRootSuperview) - topLayoutGuide);
  736. }
  737. }
  738. }
  739. //Special treatment for UICollectionView due to their cell reusing logic
  740. else if ([superScrollView isKindOfClass:[UICollectionView class]])
  741. {
  742. shouldContinue = superScrollView.contentOffset.y>0;
  743. UICollectionView *collectionView = (UICollectionView*)superScrollView;
  744. UICollectionViewCell *collectionCell = nil;
  745. NSIndexPath *indexPath = nil;
  746. NSIndexPath *previousIndexPath = nil;
  747. if (shouldContinue &&
  748. (collectionCell = (UICollectionViewCell*)[textFieldView superviewOfClassType:[UICollectionViewCell class]]) &&
  749. (indexPath = [collectionView indexPathForCell:collectionCell]) &&
  750. (previousIndexPath = [collectionView previousIndexPathOfIndexPath:indexPath]))
  751. {
  752. UICollectionViewLayoutAttributes *attributes = [collectionView layoutAttributesForItemAtIndexPath:previousIndexPath];
  753. CGRect previousCellRect = attributes.frame;
  754. if (CGRectIsEmpty(previousCellRect) == NO)
  755. {
  756. CGRect previousCellRectInRootSuperview = [collectionView convertRect:previousCellRect toView:rootController.view.superview];
  757. move = MIN(0, CGRectGetMaxY(previousCellRectInRootSuperview) - topLayoutGuide);
  758. }
  759. }
  760. }
  761. else
  762. {
  763. //If the textField is hidden at the top
  764. shouldContinue = textFieldViewRectInRootSuperview.origin.y < topLayoutGuide;
  765. if (shouldContinue) {
  766. move = MIN(0, textFieldViewRectInRootSuperview.origin.y - topLayoutGuide);
  767. }
  768. }
  769. }
  770. if (shouldContinue == NO)
  771. {
  772. move = 0;
  773. break;
  774. }
  775. UIScrollView *nextScrollView = nil;
  776. UIScrollView *tempScrollView = (UIScrollView*)[superScrollView superviewOfClassType:[UIScrollView class]];
  777. //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
  778. while (tempScrollView)
  779. {
  780. if (tempScrollView.isScrollEnabled && tempScrollView.shouldIgnoreScrollingAdjustment == NO)
  781. {
  782. nextScrollView = tempScrollView;
  783. break;
  784. }
  785. else
  786. {
  787. // Getting it's superScrollView. // (Enhancement ID: #21, #24)
  788. tempScrollView = (UIScrollView*)[tempScrollView superviewOfClassType:[UIScrollView class]];
  789. }
  790. }
  791. //Getting lastViewRect.
  792. CGRect lastViewRect = [[lastView superview] convertRect:lastView.frame toView:superScrollView];
  793. //Calculating the expected Y offset from move and scrollView's contentOffset.
  794. CGFloat shouldOffsetY = superScrollView.contentOffset.y - MIN(superScrollView.contentOffset.y,-move);
  795. //Rearranging the expected Y offset according to the view.
  796. shouldOffsetY = MIN(shouldOffsetY, lastViewRect.origin.y);
  797. //[textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
  798. //[superScrollView superviewOfClassType:[UIScrollView class]] == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierarchy.)
  799. //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
  800. if ([textFieldView respondsToSelector:@selector(isEditable)] && [textFieldView isKindOfClass:[UIScrollView class]] &&
  801. nextScrollView == nil &&
  802. (shouldOffsetY >= 0))
  803. {
  804. // Converting Rectangle according to window bounds.
  805. CGRect currentTextFieldViewRect = [[textFieldView superview] convertRect:textFieldView.frame toView:keyWindow];
  806. //Calculating expected fix distance which needs to be managed from navigation bar
  807. CGFloat expectedFixDistance = CGRectGetMinY(currentTextFieldViewRect) - topLayoutGuide;
  808. //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
  809. shouldOffsetY = MIN(shouldOffsetY, superScrollView.contentOffset.y + expectedFixDistance);
  810. //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
  811. move = 0;
  812. }
  813. else
  814. {
  815. //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
  816. move -= (shouldOffsetY-superScrollView.contentOffset.y);
  817. }
  818. CGPoint newContentOffset = CGPointMake(superScrollView.contentOffset.x, shouldOffsetY);
  819. if (CGPointEqualToPoint(superScrollView.contentOffset, newContentOffset) == NO)
  820. {
  821. __weak __typeof__(self) weakSelf = self;
  822. //Getting problem while using `setContentOffset:animated:`, So I used animation API.
  823. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  824. __strong __typeof__(self) strongSelf = weakSelf;
  825. [strongSelf showLog:[NSString stringWithFormat:@"Adjusting %.2f to %@ ContentOffset",(superScrollView.contentOffset.y-shouldOffsetY),[superScrollView _IQDescription]]];
  826. [strongSelf showLog:[NSString stringWithFormat:@"Remaining Move: %.2f",move]];
  827. BOOL animatedContentOffset = ([textFieldView superviewOfClassType:[UIStackView class] belowView:superScrollView] != nil); // (Bug ID: #1365, #1508, #1541)
  828. if (animatedContentOffset) {
  829. [superScrollView setContentOffset:newContentOffset animated:UIView.areAnimationsEnabled];
  830. } else {
  831. superScrollView.contentOffset = newContentOffset;
  832. }
  833. } completion:^(BOOL finished){
  834. __strong __typeof__(self) strongSelf = weakSelf;
  835. if ([superScrollView isKindOfClass:[UITableView class]] || [superScrollView isKindOfClass:[UICollectionView class]])
  836. {
  837. //This will update the next/previous states
  838. [strongSelf addToolbarIfRequired];
  839. }
  840. }];
  841. }
  842. // Getting next lastView & superScrollView.
  843. lastView = superScrollView;
  844. superScrollView = nextScrollView;
  845. }
  846. //Updating contentInset
  847. if (strongLastScrollView.shouldIgnoreContentInsetAdjustment == NO)
  848. {
  849. CGRect lastScrollViewRect = [[strongLastScrollView superview] convertRect:strongLastScrollView.frame toView:keyWindow];
  850. CGFloat bottomInset = (kbSize.height)-(CGRectGetHeight(keyWindow.frame)-CGRectGetMaxY(lastScrollViewRect));
  851. CGFloat bottomScrollIndicatorInset = bottomInset - keyboardDistanceFromTextField;
  852. // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
  853. bottomInset = MAX(_startingContentInsets.bottom, bottomInset);
  854. bottomScrollIndicatorInset = MAX(_startingScrollIndicatorInsets.bottom, bottomScrollIndicatorInset);
  855. if (@available(iOS 11, *)) {
  856. bottomInset -= strongLastScrollView.safeAreaInsets.bottom;
  857. bottomScrollIndicatorInset -= strongLastScrollView.safeAreaInsets.bottom;
  858. }
  859. UIEdgeInsets movedInsets = strongLastScrollView.contentInset;
  860. movedInsets.bottom = bottomInset;
  861. if (UIEdgeInsetsEqualToEdgeInsets(strongLastScrollView.contentInset, movedInsets) == NO)
  862. {
  863. [self showLog:[NSString stringWithFormat:@"old ContentInset : %@ new ContentInset : %@", NSStringFromUIEdgeInsets(strongLastScrollView.contentInset), NSStringFromUIEdgeInsets(movedInsets)]];
  864. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  865. strongLastScrollView.contentInset = movedInsets;
  866. UIEdgeInsets newScrollIndicatorInset;
  867. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  868. if (@available(iOS 11.1, *)) {
  869. newScrollIndicatorInset = strongLastScrollView.verticalScrollIndicatorInsets;
  870. } else
  871. #endif
  872. {
  873. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  874. newScrollIndicatorInset = strongLastScrollView.scrollIndicatorInsets;
  875. #endif
  876. }
  877. newScrollIndicatorInset.bottom = bottomScrollIndicatorInset;
  878. strongLastScrollView.scrollIndicatorInsets = newScrollIndicatorInset;
  879. } completion:NULL];
  880. }
  881. }
  882. }
  883. //Going ahead. No else if.
  884. }
  885. {
  886. //Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
  887. //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
  888. //[textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
  889. if ([textFieldView isKindOfClass:[UIScrollView class]] && [(UIScrollView*)textFieldView isScrollEnabled] && [textFieldView respondsToSelector:@selector(isEditable)])
  890. {
  891. UIScrollView *textView = (UIScrollView*)textFieldView;
  892. CGFloat keyboardYPosition = CGRectGetHeight(keyWindow.frame)-(kbSize.height-keyboardDistanceFromTextField);
  893. CGRect rootSuperViewFrameInWindow = [rootController.view.superview convertRect:rootController.view.superview.bounds toView:keyWindow];
  894. CGFloat keyboardOverlapping = CGRectGetMaxY(rootSuperViewFrameInWindow) - keyboardYPosition;
  895. CGFloat textViewHeight = MIN(CGRectGetHeight(textFieldView.frame), (CGRectGetHeight(rootSuperViewFrameInWindow)-topLayoutGuide-keyboardOverlapping));
  896. if (textFieldView.frame.size.height-textView.contentInset.bottom>textViewHeight)
  897. {
  898. //_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
  899. if (self.isTextViewContentInsetChanged == NO)
  900. {
  901. self.startingTextViewContentInsets = textView.contentInset;
  902. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  903. if (@available(iOS 11.1, *)) {
  904. self.startingTextViewScrollIndicatorInsets = textView.verticalScrollIndicatorInsets;
  905. } else
  906. #endif
  907. {
  908. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  909. self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets;
  910. #endif
  911. }
  912. }
  913. CGFloat bottomInset = textFieldView.frame.size.height-textViewHeight;
  914. if (@available(iOS 11, *)) {
  915. bottomInset -= textFieldView.safeAreaInsets.bottom;
  916. }
  917. UIEdgeInsets newContentInset = textView.contentInset;
  918. newContentInset.bottom = bottomInset;
  919. self.isTextViewContentInsetChanged = YES;
  920. if (UIEdgeInsetsEqualToEdgeInsets(textView.contentInset, newContentInset) == NO)
  921. {
  922. __weak __typeof__(self) weakSelf = self;
  923. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  924. __strong __typeof__(self) strongSelf = weakSelf;
  925. [strongSelf showLog:[NSString stringWithFormat:@"Old UITextView.contentInset : %@ New UITextView.contentInset : %@", NSStringFromUIEdgeInsets(textView.contentInset), NSStringFromUIEdgeInsets(textView.contentInset)]];
  926. textView.contentInset = newContentInset;
  927. textView.scrollIndicatorInsets = newContentInset;
  928. } completion:NULL];
  929. }
  930. }
  931. }
  932. {
  933. __weak __typeof__(self) weakSelf = self;
  934. // +Positive or zero.
  935. if (move>=0)
  936. {
  937. rootViewOrigin.y -= move;
  938. // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
  939. rootViewOrigin.y = MAX(rootViewOrigin.y, MIN(0, -(kbSize.height-keyboardDistanceFromTextField)));
  940. [self showLog:@"Moving Upward"];
  941. // Setting adjusted rootViewOrigin.ty
  942. //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
  943. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  944. __strong __typeof__(self) strongSelf = weakSelf;
  945. // Setting it's new frame
  946. CGRect rect = rootController.view.frame;
  947. rect.origin = rootViewOrigin;
  948. rootController.view.frame = rect;
  949. //Animating content if needed (Bug ID: #204)
  950. if (strongSelf.layoutIfNeededOnUpdate)
  951. {
  952. //Animating content (Bug ID: #160)
  953. [rootController.view setNeedsLayout];
  954. [rootController.view layoutIfNeeded];
  955. }
  956. [strongSelf showLog:[NSString stringWithFormat:@"Set %@ origin to : %@",rootController,NSStringFromCGPoint(rootViewOrigin)]];
  957. } completion:NULL];
  958. self.movedDistance = (_topViewBeginOrigin.y-rootViewOrigin.y);
  959. }
  960. // -Negative
  961. else
  962. {
  963. CGFloat disturbDistance = rootController.view.frame.origin.y-_topViewBeginOrigin.y;
  964. // disturbDistance Negative = frame disturbed. Pull Request #3
  965. // disturbDistance positive = frame not disturbed.
  966. if(disturbDistance<=0)
  967. {
  968. rootViewOrigin.y -= MAX(move, disturbDistance);
  969. [self showLog:@"Moving Downward"];
  970. // Setting adjusted rootViewRect
  971. //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
  972. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  973. __strong __typeof__(self) strongSelf = weakSelf;
  974. // Setting it's new frame
  975. CGRect rect = rootController.view.frame;
  976. rect.origin = rootViewOrigin;
  977. rootController.view.frame = rect;
  978. //Animating content if needed (Bug ID: #204)
  979. if (strongSelf.layoutIfNeededOnUpdate)
  980. {
  981. //Animating content (Bug ID: #160)
  982. [rootController.view setNeedsLayout];
  983. [rootController.view layoutIfNeeded];
  984. }
  985. [strongSelf showLog:[NSString stringWithFormat:@"Set %@ origin to : %@",rootController,NSStringFromCGPoint(rootViewOrigin)]];
  986. } completion:NULL];
  987. self.movedDistance = (_topViewBeginOrigin.y-rootController.view.frame.origin.y);
  988. }
  989. }
  990. }
  991. }
  992. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  993. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  994. }
  995. -(void)restorePosition
  996. {
  997. _hasPendingAdjustRequest = NO;
  998. // Setting rootViewController frame to it's original position. // (Bug ID: #18)
  999. if (_rootViewController && CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid) == false)
  1000. {
  1001. __weak __typeof__(self) weakSelf = self;
  1002. //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
  1003. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  1004. __strong __typeof__(self) strongSelf = weakSelf;
  1005. UIViewController *strongRootController = strongSelf.rootViewController;
  1006. {
  1007. [strongSelf showLog:[NSString stringWithFormat:@"Restoring %@ origin to : %@",strongRootController,NSStringFromCGPoint(strongSelf.topViewBeginOrigin)]];
  1008. //Restoring
  1009. CGRect rect = strongRootController.view.frame;
  1010. rect.origin = strongSelf.topViewBeginOrigin;
  1011. strongRootController.view.frame = rect;
  1012. strongSelf.movedDistance = 0;
  1013. if (strongRootController.navigationController.interactivePopGestureRecognizer.state == UIGestureRecognizerStateBegan) {
  1014. strongSelf.rootViewControllerWhilePopGestureRecognizerActive = strongRootController;
  1015. strongSelf.topViewBeginOriginWhilePopGestureRecognizerActive = strongSelf.topViewBeginOrigin;
  1016. }
  1017. //Animating content if needed (Bug ID: #204)
  1018. if (strongSelf.layoutIfNeededOnUpdate)
  1019. {
  1020. //Animating content (Bug ID: #160)
  1021. [strongRootController.view setNeedsLayout];
  1022. [strongRootController.view layoutIfNeeded];
  1023. }
  1024. }
  1025. } completion:NULL];
  1026. _rootViewController = nil;
  1027. }
  1028. }
  1029. #pragma mark - Public Methods
  1030. /* Refreshes textField/textView position if any external changes is explicitly made by user. */
  1031. - (void)reloadLayoutIfNeeded
  1032. {
  1033. if ([self privateIsEnabled] == YES)
  1034. {
  1035. UIView *textFieldView = _textFieldView;
  1036. if (textFieldView &&
  1037. _keyboardShowing == YES &&
  1038. CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid) == false &&
  1039. [textFieldView isAlertViewTextField] == NO)
  1040. {
  1041. [self optimizedAdjustPosition];
  1042. }
  1043. }
  1044. }
  1045. #pragma mark - UIKeyboad Notification methods
  1046. /* UIKeyboardWillShowNotification. */
  1047. -(void)keyboardWillShow:(NSNotification*)aNotification
  1048. {
  1049. _kbShowNotification = aNotification;
  1050. // Boolean to know keyboard is showing/hiding
  1051. _keyboardShowing = YES;
  1052. // Getting keyboard animation.
  1053. NSInteger curve = [[aNotification userInfo][UIKeyboardAnimationCurveUserInfoKey] integerValue];
  1054. _animationCurve = curve<<16;
  1055. // Getting keyboard animation duration
  1056. CGFloat duration = [[aNotification userInfo][UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1057. //Saving animation duration
  1058. if (duration != 0.0) _animationDuration = duration;
  1059. CGRect oldKBFrame = _kbFrame;
  1060. // Getting UIKeyboardSize.
  1061. _kbFrame = [[aNotification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
  1062. [self notifyKeyboardSize:_kbFrame.size];
  1063. if ([self privateIsEnabled] == NO)
  1064. {
  1065. [self restorePosition];
  1066. _topViewBeginOrigin = kIQCGPointInvalid;
  1067. return;
  1068. }
  1069. CFTimeInterval startTime = CACurrentMediaTime();
  1070. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1071. UIView *textFieldView = _textFieldView;
  1072. if (textFieldView && CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid)) // (Bug ID: #5)
  1073. {
  1074. // keyboard is not showing(At the beginning only). We should save rootViewRect.
  1075. UIViewController *rootController = [textFieldView parentContainerViewController];
  1076. _rootViewController = rootController;
  1077. if (_rootViewControllerWhilePopGestureRecognizerActive == rootController)
  1078. {
  1079. _topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive;
  1080. }
  1081. else
  1082. {
  1083. _topViewBeginOrigin = rootController.view.frame.origin;
  1084. }
  1085. _rootViewControllerWhilePopGestureRecognizerActive = nil;
  1086. _topViewBeginOriginWhilePopGestureRecognizerActive = kIQCGPointInvalid;
  1087. [self showLog:[NSString stringWithFormat:@"Saving %@ beginning origin: %@",rootController,NSStringFromCGPoint(_topViewBeginOrigin)]];
  1088. }
  1089. //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
  1090. if (!CGRectEqualToRect(_kbFrame, oldKBFrame))
  1091. {
  1092. //If _textFieldView is inside AlertView then do nothing. (Bug ID: #37, #74, #76)
  1093. //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is AlertView textField then do not affect anything (Bug ID: #70).
  1094. if (_keyboardShowing == YES &&
  1095. textFieldView &&
  1096. [textFieldView isAlertViewTextField] == NO)
  1097. {
  1098. [self optimizedAdjustPosition];
  1099. }
  1100. }
  1101. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1102. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1103. }
  1104. /* UIKeyboardDidShowNotification. */
  1105. - (void)keyboardDidShow:(NSNotification*)aNotification
  1106. {
  1107. if ([self privateIsEnabled] == NO) return;
  1108. CFTimeInterval startTime = CACurrentMediaTime();
  1109. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1110. [self showLog:[NSString stringWithFormat:@"Notification Object: %@", aNotification.object]];
  1111. UIView *textFieldView = _textFieldView;
  1112. // Getting topMost ViewController.
  1113. UIViewController *controller = [textFieldView topMostController];
  1114. //If _textFieldView viewController is presented as formSheet, then adjustPosition again because iOS internally update formSheet frame on keyboardShown. (Bug ID: #37, #74, #76)
  1115. if (_keyboardShowing == YES &&
  1116. textFieldView &&
  1117. (controller.modalPresentationStyle == UIModalPresentationFormSheet || controller.modalPresentationStyle == UIModalPresentationPageSheet) &&
  1118. [textFieldView isAlertViewTextField] == NO)
  1119. {
  1120. [self optimizedAdjustPosition];
  1121. }
  1122. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1123. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1124. }
  1125. /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
  1126. - (void)keyboardWillHide:(NSNotification*)aNotification
  1127. {
  1128. //If it's not a fake notification generated by [self setEnable:NO].
  1129. if (aNotification) _kbShowNotification = nil;
  1130. // Boolean to know keyboard is showing/hiding
  1131. _keyboardShowing = NO;
  1132. // Getting keyboard animation duration
  1133. CGFloat aDuration = [[aNotification userInfo][UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1134. if (aDuration!= 0.0f)
  1135. {
  1136. _animationDuration = aDuration;
  1137. }
  1138. //If not enabled then do nothing.
  1139. if ([self privateIsEnabled] == NO) return;
  1140. CFTimeInterval startTime = CACurrentMediaTime();
  1141. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1142. [self showLog:[NSString stringWithFormat:@"Notification Object: %@", aNotification.object]];
  1143. //Commented due to #56. Added all the conditions below to handle WKWebView's textFields. (Bug ID: #56)
  1144. // We are unable to get textField object while keyboard showing on WKWebView's textField. (Bug ID: #11)
  1145. // if (_textFieldView == nil) return;
  1146. //Restoring the contentOffset of the lastScrollView
  1147. __strong __typeof__(UIScrollView) *strongLastScrollView = _lastScrollView;
  1148. if (strongLastScrollView)
  1149. {
  1150. __weak __typeof__(self) weakSelf = self;
  1151. __weak __typeof__(UIView) *weakTextFieldView = self.textFieldView;
  1152. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  1153. __strong __typeof__(self) strongSelf = weakSelf;
  1154. __strong __typeof__(UIView) *strongTextFieldView = weakTextFieldView;
  1155. if (UIEdgeInsetsEqualToEdgeInsets(strongLastScrollView.contentInset, strongSelf.startingContentInsets) == NO)
  1156. {
  1157. [strongSelf showLog:[NSString stringWithFormat:@"Restoring ScrollView contentInset to : %@",NSStringFromUIEdgeInsets(strongSelf.startingContentInsets)]];
  1158. strongLastScrollView.contentInset = strongSelf.startingContentInsets;
  1159. strongLastScrollView.scrollIndicatorInsets = strongSelf.startingScrollIndicatorInsets;
  1160. }
  1161. if (strongLastScrollView.shouldRestoreScrollViewContentOffset && CGPointEqualToPoint(strongLastScrollView.contentOffset, strongSelf.startingContentOffset) == NO)
  1162. {
  1163. [strongSelf showLog:[NSString stringWithFormat:@"Restoring ScrollView contentOffset to : %@",NSStringFromCGPoint(strongSelf.startingContentOffset)]];
  1164. BOOL animatedContentOffset = ([strongTextFieldView superviewOfClassType:[UIStackView class] belowView:strongLastScrollView] != nil); // (Bug ID: #1365, #1508, #1541)
  1165. if (animatedContentOffset) {
  1166. [strongLastScrollView setContentOffset:strongSelf.startingContentOffset animated:UIView.areAnimationsEnabled];
  1167. } else {
  1168. strongLastScrollView.contentOffset = strongSelf.startingContentOffset;
  1169. }
  1170. }
  1171. // TODO: restore scrollView state
  1172. // This is temporary solution. Have to implement the save and restore scrollView state
  1173. UIScrollView *superscrollView = strongLastScrollView;
  1174. do
  1175. {
  1176. CGSize contentSize = CGSizeMake(MAX(superscrollView.contentSize.width, CGRectGetWidth(superscrollView.frame)), MAX(superscrollView.contentSize.height, CGRectGetHeight(superscrollView.frame)));
  1177. CGFloat minimumY = contentSize.height-CGRectGetHeight(superscrollView.frame);
  1178. if (minimumY<superscrollView.contentOffset.y)
  1179. {
  1180. CGPoint newContentOffset = CGPointMake(superscrollView.contentOffset.x, minimumY);
  1181. if (CGPointEqualToPoint(superscrollView.contentOffset, newContentOffset) == NO)
  1182. {
  1183. [self showLog:[NSString stringWithFormat:@"Restoring contentOffset to : %@",NSStringFromCGPoint(newContentOffset)]];
  1184. BOOL animatedContentOffset = ([strongSelf.textFieldView superviewOfClassType:[UIStackView class] belowView:superscrollView] != nil); // (Bug ID: #1365, #1508, #1541)
  1185. if (animatedContentOffset) {
  1186. [superscrollView setContentOffset:newContentOffset animated:UIView.areAnimationsEnabled];
  1187. } else {
  1188. superscrollView.contentOffset = newContentOffset;
  1189. }
  1190. }
  1191. }
  1192. } while ((superscrollView = (UIScrollView*)[superscrollView superviewOfClassType:[UIScrollView class]]));
  1193. } completion:NULL];
  1194. }
  1195. [self restorePosition];
  1196. //Reset all values
  1197. _lastScrollView = nil;
  1198. _kbFrame = CGRectZero;
  1199. [self notifyKeyboardSize:_kbFrame.size];
  1200. _startingContentInsets = UIEdgeInsetsZero;
  1201. _startingScrollIndicatorInsets = UIEdgeInsetsZero;
  1202. _startingContentOffset = CGPointZero;
  1203. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1204. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1205. }
  1206. /* UIKeyboardDidHideNotification. So topViewBeginRect can be set to CGRectZero. */
  1207. - (void)keyboardDidHide:(NSNotification*)aNotification
  1208. {
  1209. CFTimeInterval startTime = CACurrentMediaTime();
  1210. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1211. [self showLog:[NSString stringWithFormat:@"Notification Object: %@", aNotification.object]];
  1212. _topViewBeginOrigin = kIQCGPointInvalid;
  1213. _kbFrame = CGRectZero;
  1214. [self notifyKeyboardSize:_kbFrame.size];
  1215. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1216. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1217. }
  1218. -(void)registerKeyboardSizeChangeWithIdentifier:(nonnull id<NSCopying>)identifier sizeHandler:(void (^_Nonnull)(CGSize size))sizeHandler
  1219. {
  1220. _keyboardSizeObservers[identifier] = sizeHandler;
  1221. }
  1222. -(void)unregisterKeyboardSizeChangeWithIdentifier:(nonnull id<NSCopying>)identifier
  1223. {
  1224. _keyboardSizeObservers[identifier] = nil;
  1225. }
  1226. -(void)notifyKeyboardSize:(CGSize)size
  1227. {
  1228. if (!CGSizeEqualToSize(size, _keyboardLastNotifySize)) {
  1229. _keyboardLastNotifySize = size;
  1230. for (SizeBlock block in _keyboardSizeObservers.allValues) {
  1231. block(size);
  1232. }
  1233. }
  1234. }
  1235. #pragma mark - UITextFieldView Delegate methods
  1236. /** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
  1237. -(void)textFieldViewDidBeginEditing:(NSNotification*)notification
  1238. {
  1239. UIView *object = (UIView*)notification.object;
  1240. if (object.window.isKeyWindow == NO) {
  1241. return;
  1242. }
  1243. CFTimeInterval startTime = CACurrentMediaTime();
  1244. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1245. [self showLog:[NSString stringWithFormat:@"Notification Object: %@", notification.object]];
  1246. // Getting object
  1247. _textFieldView = object;
  1248. UIView *textFieldView = _textFieldView;
  1249. if (_overrideKeyboardAppearance == YES)
  1250. {
  1251. UITextField *textField = (UITextField*)textFieldView;
  1252. if ([textField respondsToSelector:@selector(keyboardAppearance)])
  1253. {
  1254. //If keyboard appearance is not like the provided appearance
  1255. if (textField.keyboardAppearance != _keyboardAppearance)
  1256. {
  1257. //Setting textField keyboard appearance and reloading inputViews.
  1258. textField.keyboardAppearance = _keyboardAppearance;
  1259. [textField reloadInputViews];
  1260. }
  1261. }
  1262. }
  1263. //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
  1264. if ([self privateIsEnableAutoToolbar])
  1265. {
  1266. //UITextView special case. Keyboard Notification is firing before textView notification so we need to reload it's inputViews.
  1267. if ([textFieldView respondsToSelector:@selector(isEditable)] && [textFieldView isKindOfClass:[UIScrollView class]] &&
  1268. textFieldView.inputAccessoryView == nil)
  1269. {
  1270. __weak __typeof__(self) weakSelf = self;
  1271. [UIView animateWithDuration:0.00001 delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  1272. __strong __typeof__(self) strongSelf = weakSelf;
  1273. [strongSelf addToolbarIfRequired];
  1274. } completion:^(BOOL finished) {
  1275. __strong __typeof__(self) strongSelf = weakSelf;
  1276. //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
  1277. [strongSelf.textFieldView reloadInputViews];
  1278. }];
  1279. }
  1280. //Else adding toolbar
  1281. else
  1282. {
  1283. [self addToolbarIfRequired];
  1284. }
  1285. }
  1286. else
  1287. {
  1288. [self removeToolbarIfRequired];
  1289. }
  1290. //Adding Geture recognizer to window (Enhancement ID: #14)
  1291. [_resignFirstResponderGesture setEnabled:[self privateShouldResignOnTouchOutside]];
  1292. [textFieldView.window addGestureRecognizer:_resignFirstResponderGesture];
  1293. if ([self privateIsEnabled] == NO)
  1294. {
  1295. [self restorePosition];
  1296. _topViewBeginOrigin = kIQCGPointInvalid;
  1297. }
  1298. else
  1299. {
  1300. if (CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid)) // (Bug ID: #5)
  1301. {
  1302. // keyboard is not showing(At the beginning only).
  1303. UIViewController *rootController = [textFieldView parentContainerViewController];
  1304. _rootViewController = rootController;
  1305. if (_rootViewControllerWhilePopGestureRecognizerActive == rootController)
  1306. {
  1307. _topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive;
  1308. }
  1309. else
  1310. {
  1311. _topViewBeginOrigin = rootController.view.frame.origin;
  1312. }
  1313. _rootViewControllerWhilePopGestureRecognizerActive = nil;
  1314. _topViewBeginOriginWhilePopGestureRecognizerActive = kIQCGPointInvalid;
  1315. [self showLog:[NSString stringWithFormat:@"Saving %@ beginning origin: %@",rootController, NSStringFromCGPoint(_topViewBeginOrigin)]];
  1316. }
  1317. //If textFieldView is inside AlertView then do nothing. (Bug ID: #37, #74, #76)
  1318. //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is AlertView textField then do not affect anything (Bug ID: #70).
  1319. if (_keyboardShowing == YES &&
  1320. textFieldView &&
  1321. [textFieldView isAlertViewTextField] == NO)
  1322. {
  1323. // keyboard is already showing. adjust frame.
  1324. [self optimizedAdjustPosition];
  1325. }
  1326. }
  1327. // if ([textFieldView isKindOfClass:[UITextField class]])
  1328. // {
  1329. // [(UITextField*)textFieldView addTarget:self action:@selector(editingDidEndOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
  1330. // }
  1331. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1332. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1333. }
  1334. /** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
  1335. -(void)textFieldViewDidEndEditing:(NSNotification*)notification
  1336. {
  1337. UIView *object = (UIView*)notification.object;
  1338. if (object.window.isKeyWindow == NO) {
  1339. return;
  1340. }
  1341. CFTimeInterval startTime = CACurrentMediaTime();
  1342. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1343. [self showLog:[NSString stringWithFormat:@"Notification Object: %@", notification.object]];
  1344. UIView *textFieldView = _textFieldView;
  1345. //Removing gesture recognizer (Enhancement ID: #14)
  1346. [textFieldView.window removeGestureRecognizer:_resignFirstResponderGesture];
  1347. // if ([textFieldView isKindOfClass:[UITextField class]])
  1348. // {
  1349. // [(UITextField*)textFieldView removeTarget:self action:@selector(editingDidEndOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
  1350. // }
  1351. // We check if there's a change in original frame or not.
  1352. if(_isTextViewContentInsetChanged == YES &&
  1353. [textFieldView respondsToSelector:@selector(isEditable)] && [textFieldView isKindOfClass:[UIScrollView class]])
  1354. {
  1355. UIScrollView *textView = (UIScrollView*)textFieldView;
  1356. self.isTextViewContentInsetChanged = NO;
  1357. if (UIEdgeInsetsEqualToEdgeInsets(textView.contentInset, self.startingTextViewContentInsets) == NO)
  1358. {
  1359. __weak __typeof__(self) weakSelf = self;
  1360. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  1361. __strong __typeof__(self) strongSelf = weakSelf;
  1362. [strongSelf showLog:[NSString stringWithFormat:@"Restoring textView.contentInset to : %@",NSStringFromUIEdgeInsets(strongSelf.startingTextViewContentInsets)]];
  1363. //Setting textField to it's initial contentInset
  1364. textView.contentInset = strongSelf.startingTextViewContentInsets;
  1365. textView.scrollIndicatorInsets = strongSelf.startingTextViewScrollIndicatorInsets;
  1366. } completion:NULL];
  1367. }
  1368. }
  1369. //Setting object to nil
  1370. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 160000
  1371. if (@available(iOS 16.0, *)) {
  1372. if ([textFieldView isKindOfClass:[UITextView class]] && [(UITextView*)textFieldView isFindInteractionEnabled]) {
  1373. //Not setting it nil, because it may be doing find interaction.
  1374. //As of now, here textView.findInteraction.isFindNavigatorVisible returns NO
  1375. //So there is no way to detect if this is dismissed due to findInteraction
  1376. } else {
  1377. textFieldView = nil;
  1378. }
  1379. } else
  1380. #endif
  1381. {
  1382. textFieldView = nil;
  1383. }
  1384. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1385. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1386. }
  1387. //-(void)editingDidEndOnExit:(UITextField*)textField
  1388. //{
  1389. // [self showLog:[NSString stringWithFormat:@"ReturnKey %@",NSStringFromSelector(_cmd)]];
  1390. //}
  1391. #pragma mark - UIStatusBar Notification methods
  1392. /** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
  1393. - (void)willChangeStatusBarOrientation:(NSNotification*)aNotification
  1394. {
  1395. UIInterfaceOrientation currentStatusBarOrientation = UIInterfaceOrientationUnknown;
  1396. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  1397. if (@available(iOS 13.0, *)) {
  1398. currentStatusBarOrientation = [self keyWindow].windowScene.interfaceOrientation;
  1399. } else
  1400. #endif
  1401. {
  1402. #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
  1403. currentStatusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;
  1404. #endif
  1405. }
  1406. #pragma clang diagnostic push
  1407. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1408. UIInterfaceOrientation statusBarOrientation = [aNotification.userInfo[UIApplicationStatusBarOrientationUserInfoKey] integerValue];
  1409. #pragma clang diagnostic pop
  1410. if (statusBarOrientation != currentStatusBarOrientation) {
  1411. return;
  1412. }
  1413. CFTimeInterval startTime = CACurrentMediaTime();
  1414. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1415. [self showLog:[NSString stringWithFormat:@"Notification Object: %@", aNotification.object]];
  1416. __strong __typeof__(UIView) *strongTextFieldView = _textFieldView;
  1417. //If textViewContentInsetChanged is changed then restore it.
  1418. if (_isTextViewContentInsetChanged == YES &&
  1419. [strongTextFieldView respondsToSelector:@selector(isEditable)] && [strongTextFieldView isKindOfClass:[UIScrollView class]])
  1420. {
  1421. UIScrollView *textView = (UIScrollView*)strongTextFieldView;
  1422. self.isTextViewContentInsetChanged = NO;
  1423. if (UIEdgeInsetsEqualToEdgeInsets(textView.contentInset, self.startingTextViewContentInsets) == NO)
  1424. {
  1425. __weak __typeof__(self) weakSelf = self;
  1426. //Due to orientation callback we need to set it's original position.
  1427. [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{
  1428. __strong __typeof__(self) strongSelf = weakSelf;
  1429. [strongSelf showLog:[NSString stringWithFormat:@"Restoring textView.contentInset to : %@",NSStringFromUIEdgeInsets(strongSelf.startingTextViewContentInsets)]];
  1430. //Setting textField to it's initial contentInset
  1431. textView.contentInset = strongSelf.startingTextViewContentInsets;
  1432. textView.scrollIndicatorInsets = strongSelf.startingTextViewScrollIndicatorInsets;
  1433. } completion:NULL];
  1434. }
  1435. }
  1436. [self restorePosition];
  1437. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1438. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1439. }
  1440. #pragma mark AutoResign methods
  1441. /** Resigning on tap gesture. */
  1442. - (void)tapRecognized:(UITapGestureRecognizer*)gesture // (Enhancement ID: #14)
  1443. {
  1444. if (gesture.state == UIGestureRecognizerStateEnded)
  1445. {
  1446. //Resigning currently responder textField.
  1447. [self resignFirstResponder];
  1448. }
  1449. }
  1450. /** 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. */
  1451. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
  1452. {
  1453. return NO;
  1454. }
  1455. /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
  1456. -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  1457. {
  1458. // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
  1459. for (Class aClass in self.touchResignedGestureIgnoreClasses)
  1460. {
  1461. if ([[touch view] isKindOfClass:aClass])
  1462. {
  1463. return NO;
  1464. }
  1465. }
  1466. return YES;
  1467. }
  1468. /** Resigning textField. */
  1469. - (BOOL)resignFirstResponder
  1470. {
  1471. UIView *textFieldView = _textFieldView;
  1472. if (textFieldView)
  1473. {
  1474. // Retaining textFieldView
  1475. UIView *textFieldRetain = textFieldView;
  1476. //Resigning first responder
  1477. BOOL isResignFirstResponder = [textFieldView resignFirstResponder];
  1478. // If it refuses then becoming it as first responder again. (Bug ID: #96)
  1479. if (isResignFirstResponder == NO)
  1480. {
  1481. //If it refuses to resign then becoming it first responder again for getting notifications callback.
  1482. [textFieldRetain becomeFirstResponder];
  1483. [self showLog:[NSString stringWithFormat:@"Refuses to Resign first responder: %@",textFieldView]];
  1484. }
  1485. return isResignFirstResponder;
  1486. }
  1487. else
  1488. {
  1489. return NO;
  1490. }
  1491. }
  1492. /** Returns YES if can navigate to previous responder textField/textView, otherwise NO. */
  1493. -(BOOL)canGoPrevious
  1494. {
  1495. //Getting all responder view's.
  1496. NSArray<UIView*> *textFields = [self responderViews];
  1497. //Getting index of current textField.
  1498. NSUInteger index = [textFields indexOfObject:_textFieldView];
  1499. //If it is not first textField. then it's previous object can becomeFirstResponder.
  1500. if (index != NSNotFound &&
  1501. index > 0)
  1502. {
  1503. return YES;
  1504. }
  1505. else
  1506. {
  1507. return NO;
  1508. }
  1509. }
  1510. /** Returns YES if can navigate to next responder textField/textView, otherwise NO. */
  1511. -(BOOL)canGoNext
  1512. {
  1513. //Getting all responder view's.
  1514. NSArray<UIView*> *textFields = [self responderViews];
  1515. //Getting index of current textField.
  1516. NSUInteger index = [textFields indexOfObject:_textFieldView];
  1517. //If it is not last textField. then it's next object becomeFirstResponder.
  1518. if (index != NSNotFound &&
  1519. index < textFields.count-1)
  1520. {
  1521. return YES;
  1522. }
  1523. else
  1524. {
  1525. return NO;
  1526. }
  1527. }
  1528. /** Navigate to previous responder textField/textView. */
  1529. -(BOOL)goPrevious
  1530. {
  1531. //Getting all responder view's.
  1532. NSArray<__kindof UIView*> *textFields = [self responderViews];
  1533. //Getting index of current textField.
  1534. NSUInteger index = [textFields indexOfObject:_textFieldView];
  1535. //If it is not first textField. then it's previous object becomeFirstResponder.
  1536. if (index != NSNotFound &&
  1537. index > 0)
  1538. {
  1539. UITextField *nextTextField = textFields[index-1];
  1540. BOOL isAcceptAsFirstResponder = [nextTextField becomeFirstResponder];
  1541. // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
  1542. if (isAcceptAsFirstResponder == NO)
  1543. {
  1544. [self showLog:[NSString stringWithFormat:@"Refuses to become first responder: %@",nextTextField]];
  1545. }
  1546. return isAcceptAsFirstResponder;
  1547. }
  1548. else
  1549. {
  1550. return NO;
  1551. }
  1552. }
  1553. /** Navigate to next responder textField/textView. */
  1554. -(BOOL)goNext
  1555. {
  1556. //Getting all responder view's.
  1557. NSArray<__kindof UIView*> *textFields = [self responderViews];
  1558. //Getting index of current textField.
  1559. NSUInteger index = [textFields indexOfObject:_textFieldView];
  1560. //If it is not last textField. then it's next object becomeFirstResponder.
  1561. if (index != NSNotFound &&
  1562. index < textFields.count-1)
  1563. {
  1564. UITextField *nextTextField = textFields[index+1];
  1565. BOOL isAcceptAsFirstResponder = [nextTextField becomeFirstResponder];
  1566. // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
  1567. if (isAcceptAsFirstResponder == NO)
  1568. {
  1569. [self showLog:[NSString stringWithFormat:@"Refuses to become first responder: %@",nextTextField]];
  1570. }
  1571. return isAcceptAsFirstResponder;
  1572. }
  1573. else
  1574. {
  1575. return NO;
  1576. }
  1577. }
  1578. #pragma mark AutoToolbar methods
  1579. /** Get all UITextField/UITextView siblings of textFieldView. */
  1580. -(NSArray<__kindof UIView*>*)responderViews
  1581. {
  1582. UIView *superConsideredView;
  1583. UIView *textFieldView = _textFieldView;
  1584. //If find any consider responderView in it's upper hierarchy then will get deepResponderView.
  1585. for (Class consideredClass in _toolbarPreviousNextAllowedClasses)
  1586. {
  1587. superConsideredView = [textFieldView superviewOfClassType:consideredClass];
  1588. if (superConsideredView)
  1589. break;
  1590. }
  1591. //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
  1592. if (superConsideredView)
  1593. {
  1594. return [superConsideredView deepResponderViews];
  1595. }
  1596. //Otherwise fetching all the siblings
  1597. else
  1598. {
  1599. NSArray<UIView*> *textFields = [textFieldView responderSiblings];
  1600. //Sorting textFields according to behaviour
  1601. switch (_toolbarManageBehaviour)
  1602. {
  1603. //If autoToolbar behaviour is bySubviews, then returning it.
  1604. case IQAutoToolbarBySubviews:
  1605. return textFields;
  1606. break;
  1607. //If autoToolbar behaviour is by tag, then sorting it according to tag property.
  1608. case IQAutoToolbarByTag:
  1609. return [textFields sortedArrayByTag];
  1610. break;
  1611. //If autoToolbar behaviour is by tag, then sorting it according to tag property.
  1612. case IQAutoToolbarByPosition:
  1613. return [textFields sortedArrayByPosition];
  1614. break;
  1615. default:
  1616. return nil;
  1617. break;
  1618. }
  1619. }
  1620. }
  1621. /** Add toolbar if it is required to add on textFields and it's siblings. */
  1622. -(void)addToolbarIfRequired
  1623. {
  1624. CFTimeInterval startTime = CACurrentMediaTime();
  1625. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1626. // Getting all the sibling textFields.
  1627. NSArray<UIView*> *siblings = [self responderViews];
  1628. [self showLog:[NSString stringWithFormat:@"Found %lu responder sibling(s)",(unsigned long)siblings.count]];
  1629. UIView *textFieldView = _textFieldView;
  1630. //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
  1631. //setInputAccessoryView: check (Bug ID: #307)
  1632. if ([textFieldView respondsToSelector:@selector(setInputAccessoryView:)])
  1633. {
  1634. if ([textFieldView inputAccessoryView] == nil ||
  1635. [[textFieldView inputAccessoryView] tag] == kIQPreviousNextButtonToolbarTag ||
  1636. [[textFieldView inputAccessoryView] tag] == kIQDoneButtonToolbarTag)
  1637. {
  1638. UITextField *textField = (UITextField*)textFieldView;
  1639. IQBarButtonItemConfiguration *rightConfiguration = nil;
  1640. //Supporting Custom Done button image (Enhancement ID: #366)
  1641. if (_toolbarDoneBarButtonItemImage)
  1642. {
  1643. rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:_toolbarDoneBarButtonItemImage action:@selector(doneAction:)];
  1644. }
  1645. //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
  1646. else if (_toolbarDoneBarButtonItemText)
  1647. {
  1648. rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:_toolbarDoneBarButtonItemText action:@selector(doneAction:)];
  1649. }
  1650. else
  1651. {
  1652. rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone action:@selector(doneAction:)];
  1653. }
  1654. rightConfiguration.accessibilityLabel = _toolbarDoneBarButtonItemAccessibilityLabel ? : @"Done";
  1655. // If only one object is found, then adding only Done button.
  1656. if ((siblings.count <= 1 && self.previousNextDisplayMode == IQPreviousNextDisplayModeDefault) || self.previousNextDisplayMode == IQPreviousNextDisplayModeAlwaysHide)
  1657. {
  1658. [textField addKeyboardToolbarWithTarget:self titleText:(_shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder : nil) rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:nil nextBarButtonConfiguration:nil];
  1659. textField.inputAccessoryView.tag = kIQDoneButtonToolbarTag; // (Bug ID: #78)
  1660. }
  1661. //If there is multiple siblings of textField
  1662. else if ((self.previousNextDisplayMode == IQPreviousNextDisplayModeDefault) || self.previousNextDisplayMode == IQPreviousNextDisplayModeAlwaysShow)
  1663. {
  1664. IQBarButtonItemConfiguration *prevConfiguration = nil;
  1665. //Supporting Custom Done button image (Enhancement ID: #366)
  1666. if (_toolbarPreviousBarButtonItemImage)
  1667. {
  1668. prevConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:_toolbarPreviousBarButtonItemImage action:@selector(previousAction:)];
  1669. }
  1670. //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
  1671. else if (_toolbarPreviousBarButtonItemText)
  1672. {
  1673. prevConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:_toolbarPreviousBarButtonItemText action:@selector(previousAction:)];
  1674. }
  1675. else
  1676. {
  1677. prevConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardPreviousImage] action:@selector(previousAction:)];
  1678. }
  1679. prevConfiguration.accessibilityLabel = _toolbarPreviousBarButtonItemAccessibilityLabel ? : @"Previous";
  1680. IQBarButtonItemConfiguration *nextConfiguration = nil;
  1681. //Supporting Custom Done button image (Enhancement ID: #366)
  1682. if (_toolbarNextBarButtonItemImage)
  1683. {
  1684. nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:_toolbarNextBarButtonItemImage action:@selector(nextAction:)];
  1685. }
  1686. //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
  1687. else if (_toolbarNextBarButtonItemText)
  1688. {
  1689. nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:_toolbarNextBarButtonItemText action:@selector(nextAction:)];
  1690. }
  1691. else
  1692. {
  1693. nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardNextImage] action:@selector(nextAction:)];
  1694. }
  1695. nextConfiguration.accessibilityLabel = _toolbarNextBarButtonItemAccessibilityLabel ? : @"Next";
  1696. [textField addKeyboardToolbarWithTarget:self titleText:(_shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder : nil) rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:prevConfiguration nextBarButtonConfiguration:nextConfiguration];
  1697. textField.inputAccessoryView.tag = kIQPreviousNextButtonToolbarTag; // (Bug ID: #78)
  1698. }
  1699. IQToolbar *toolbar = textField.keyboardToolbar;
  1700. //Bar style according to keyboard appearance
  1701. if ([textField respondsToSelector:@selector(keyboardAppearance)])
  1702. {
  1703. //Setting toolbar tintColor // (Enhancement ID: #30)
  1704. if (_shouldToolbarUsesTextFieldTintColor)
  1705. {
  1706. toolbar.tintColor = [textField tintColor];
  1707. }
  1708. else if (_toolbarTintColor)
  1709. {
  1710. toolbar.tintColor = _toolbarTintColor;
  1711. }
  1712. else
  1713. {
  1714. toolbar.tintColor = nil;
  1715. }
  1716. switch ([textField keyboardAppearance])
  1717. {
  1718. case UIKeyboardAppearanceDark:
  1719. {
  1720. toolbar.barStyle = UIBarStyleBlack;
  1721. [toolbar setBarTintColor:nil];
  1722. }
  1723. break;
  1724. default:
  1725. {
  1726. toolbar.barStyle = UIBarStyleDefault;
  1727. toolbar.barTintColor = _toolbarBarTintColor;
  1728. }
  1729. break;
  1730. }
  1731. //If need to show placeholder
  1732. if (_shouldShowToolbarPlaceholder &&
  1733. textField.shouldHideToolbarPlaceholder == NO)
  1734. {
  1735. //Updating placeholder //(Bug ID: #148, #272)
  1736. if (toolbar.titleBarButton.title == nil ||
  1737. [toolbar.titleBarButton.title isEqualToString:textField.drawingToolbarPlaceholder] == NO)
  1738. {
  1739. [toolbar.titleBarButton setTitle:textField.drawingToolbarPlaceholder];
  1740. }
  1741. //Setting toolbar title font. // (Enhancement ID: #30)
  1742. if (_placeholderFont &&
  1743. [_placeholderFont isKindOfClass:[UIFont class]])
  1744. {
  1745. [toolbar.titleBarButton setTitleFont:_placeholderFont];
  1746. }
  1747. //Setting toolbar title color. // (Enhancement ID: #880)
  1748. if (_placeholderColor)
  1749. {
  1750. [toolbar.titleBarButton setTitleColor:_placeholderColor];
  1751. }
  1752. //Setting toolbar button title color. // (Enhancement ID: #880)
  1753. if (_placeholderButtonColor)
  1754. {
  1755. [toolbar.titleBarButton setSelectableTitleColor:_placeholderButtonColor];
  1756. }
  1757. }
  1758. else
  1759. {
  1760. //Updating placeholder //(Bug ID: #272)
  1761. toolbar.titleBarButton.title = nil;
  1762. }
  1763. }
  1764. //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
  1765. // If firstTextField, then previous should not be enabled.
  1766. if (siblings.firstObject == textField)
  1767. {
  1768. if (siblings.count == 1)
  1769. {
  1770. textField.keyboardToolbar.previousBarButton.enabled = NO;
  1771. textField.keyboardToolbar.nextBarButton.enabled = NO;
  1772. }
  1773. else
  1774. {
  1775. textField.keyboardToolbar.previousBarButton.enabled = NO;
  1776. textField.keyboardToolbar.nextBarButton.enabled = YES;
  1777. }
  1778. }
  1779. // If lastTextField then next should not be enaled.
  1780. else if ([siblings lastObject] == textField)
  1781. {
  1782. textField.keyboardToolbar.previousBarButton.enabled = YES;
  1783. textField.keyboardToolbar.nextBarButton.enabled = NO;
  1784. }
  1785. else
  1786. {
  1787. textField.keyboardToolbar.previousBarButton.enabled = YES;
  1788. textField.keyboardToolbar.nextBarButton.enabled = YES;
  1789. }
  1790. }
  1791. }
  1792. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1793. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1794. }
  1795. /** Remove any toolbar if it is IQToolbar. */
  1796. -(void)removeToolbarIfRequired // (Bug ID: #18)
  1797. {
  1798. CFTimeInterval startTime = CACurrentMediaTime();
  1799. [self showLog:[NSString stringWithFormat:@">>>>> %@ started >>>>>",NSStringFromSelector(_cmd)] indentation:1];
  1800. // Getting all the sibling textFields.
  1801. NSArray<UIView*> *siblings = [self responderViews];
  1802. [self showLog:[NSString stringWithFormat:@"Found %lu responder sibling(s)",(unsigned long)siblings.count]];
  1803. for (UITextField *textField in siblings)
  1804. {
  1805. UIView *toolbar = [textField inputAccessoryView];
  1806. // (Bug ID: #78)
  1807. //setInputAccessoryView: check (Bug ID: #307)
  1808. if ([textField respondsToSelector:@selector(setInputAccessoryView:)] &&
  1809. ([toolbar isKindOfClass:[IQToolbar class]] && (toolbar.tag == kIQDoneButtonToolbarTag || toolbar.tag == kIQPreviousNextButtonToolbarTag)))
  1810. {
  1811. textField.inputAccessoryView = nil;
  1812. [textField reloadInputViews];
  1813. }
  1814. }
  1815. CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
  1816. [self showLog:[NSString stringWithFormat:@"<<<<< %@ ended: %g seconds <<<<<",NSStringFromSelector(_cmd),elapsedTime] indentation:-1];
  1817. }
  1818. /** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
  1819. - (void)reloadInputViews
  1820. {
  1821. //If enabled then adding toolbar.
  1822. if ([self privateIsEnableAutoToolbar] == YES)
  1823. {
  1824. [self addToolbarIfRequired];
  1825. }
  1826. //Else removing toolbar.
  1827. else
  1828. {
  1829. [self removeToolbarIfRequired];
  1830. }
  1831. }
  1832. #pragma mark previous/next/done functionality
  1833. /** previousAction. */
  1834. -(void)previousAction:(IQBarButtonItem*)barButton
  1835. {
  1836. //If user wants to play input Click sound. Then Play Input Click Sound.
  1837. if (_shouldPlayInputClicks)
  1838. {
  1839. [[UIDevice currentDevice] playInputClick];
  1840. }
  1841. if ([self canGoPrevious])
  1842. {
  1843. UIView *currentTextFieldView = _textFieldView;
  1844. BOOL isAcceptAsFirstResponder = [self goPrevious];
  1845. NSInvocation *invocation = barButton.invocation;
  1846. UIView *sender = currentTextFieldView;
  1847. //Handling search bar special case
  1848. {
  1849. UISearchBar *searchBar = currentTextFieldView.textFieldSearchBar;
  1850. if (searchBar)
  1851. {
  1852. invocation = searchBar.keyboardToolbar.previousBarButton.invocation;
  1853. sender = searchBar;
  1854. }
  1855. }
  1856. if (isAcceptAsFirstResponder == YES && invocation)
  1857. {
  1858. if (invocation.methodSignature.numberOfArguments > 2)
  1859. {
  1860. [invocation setArgument:&sender atIndex:2];
  1861. }
  1862. [invocation invoke];
  1863. }
  1864. }
  1865. }
  1866. /** nextAction. */
  1867. -(void)nextAction:(IQBarButtonItem*)barButton
  1868. {
  1869. //If user wants to play input Click sound. Then Play Input Click Sound.
  1870. if (_shouldPlayInputClicks)
  1871. {
  1872. [[UIDevice currentDevice] playInputClick];
  1873. }
  1874. if ([self canGoNext])
  1875. {
  1876. UIView *currentTextFieldView = _textFieldView;
  1877. BOOL isAcceptAsFirstResponder = [self goNext];
  1878. NSInvocation *invocation = barButton.invocation;
  1879. UIView *sender = currentTextFieldView;
  1880. //Handling search bar special case
  1881. {
  1882. UISearchBar *searchBar = currentTextFieldView.textFieldSearchBar;
  1883. if (searchBar)
  1884. {
  1885. invocation = searchBar.keyboardToolbar.nextBarButton.invocation;
  1886. sender = searchBar;
  1887. }
  1888. }
  1889. if (isAcceptAsFirstResponder == YES && invocation)
  1890. {
  1891. if (invocation.methodSignature.numberOfArguments > 2)
  1892. {
  1893. [invocation setArgument:&sender atIndex:2];
  1894. }
  1895. [invocation invoke];
  1896. }
  1897. }
  1898. }
  1899. /** doneAction. Resigning current textField. */
  1900. -(void)doneAction:(IQBarButtonItem*)barButton
  1901. {
  1902. //If user wants to play input Click sound. Then Play Input Click Sound.
  1903. if (_shouldPlayInputClicks)
  1904. {
  1905. [[UIDevice currentDevice] playInputClick];
  1906. }
  1907. UIView *currentTextFieldView = _textFieldView;
  1908. BOOL isResignedFirstResponder = [self resignFirstResponder];
  1909. NSInvocation *invocation = barButton.invocation;
  1910. UIView *sender = currentTextFieldView;
  1911. //Handling search bar special case
  1912. {
  1913. UISearchBar *searchBar = currentTextFieldView.textFieldSearchBar;
  1914. if (searchBar)
  1915. {
  1916. invocation = searchBar.keyboardToolbar.doneBarButton.invocation;
  1917. sender = searchBar;
  1918. }
  1919. }
  1920. if (isResignedFirstResponder == YES && invocation)
  1921. {
  1922. if (invocation.methodSignature.numberOfArguments > 2)
  1923. {
  1924. [invocation setArgument:&sender atIndex:2];
  1925. }
  1926. [invocation invoke];
  1927. }
  1928. }
  1929. #pragma mark - Customised textField/textView support.
  1930. /**
  1931. Add customised Notification for third party customised TextField/TextView.
  1932. */
  1933. -(void)registerTextFieldViewClass:(nonnull Class)aClass
  1934. didBeginEditingNotificationName:(nonnull NSString *)didBeginEditingNotificationName
  1935. didEndEditingNotificationName:(nonnull NSString *)didEndEditingNotificationName
  1936. {
  1937. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidBeginEditing:) name:didBeginEditingNotificationName object:nil];
  1938. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidEndEditing:) name:didEndEditingNotificationName object:nil];
  1939. }
  1940. /**
  1941. Remove customised Notification for third party customised TextField/TextView.
  1942. */
  1943. -(void)unregisterTextFieldViewClass:(nonnull Class)aClass
  1944. didBeginEditingNotificationName:(nonnull NSString *)didBeginEditingNotificationName
  1945. didEndEditingNotificationName:(nonnull NSString *)didEndEditingNotificationName
  1946. {
  1947. [[NSNotificationCenter defaultCenter] removeObserver:self name:didBeginEditingNotificationName object:nil];
  1948. [[NSNotificationCenter defaultCenter] removeObserver:self name:didEndEditingNotificationName object:nil];
  1949. }
  1950. -(void)registerAllNotifications
  1951. {
  1952. // Registering for keyboard notification.
  1953. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  1954. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
  1955. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  1956. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
  1957. // Registering for UITextField notification.
  1958. [self registerTextFieldViewClass:[UITextField class]
  1959. didBeginEditingNotificationName:UITextFieldTextDidBeginEditingNotification
  1960. didEndEditingNotificationName:UITextFieldTextDidEndEditingNotification];
  1961. // Registering for UITextView notification.
  1962. [self registerTextFieldViewClass:[UITextView class]
  1963. didBeginEditingNotificationName:UITextViewTextDidBeginEditingNotification
  1964. didEndEditingNotificationName:UITextViewTextDidEndEditingNotification];
  1965. // Registering for orientation changes notification
  1966. #pragma clang diagnostic push
  1967. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1968. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willChangeStatusBarOrientation:) name:UIApplicationWillChangeStatusBarOrientationNotification object:[UIApplication sharedApplication]];
  1969. #pragma clang diagnostic pop
  1970. }
  1971. -(void)unregisterAllNotifications
  1972. {
  1973. // Unregistering for keyboard notification.
  1974. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  1975. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
  1976. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
  1977. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
  1978. // Unregistering for UITextField notification.
  1979. [self unregisterTextFieldViewClass:[UITextField class]
  1980. didBeginEditingNotificationName:UITextFieldTextDidBeginEditingNotification
  1981. didEndEditingNotificationName:UITextFieldTextDidEndEditingNotification];
  1982. // Unregistering for UITextView notification.
  1983. [self unregisterTextFieldViewClass:[UITextView class]
  1984. didBeginEditingNotificationName:UITextViewTextDidBeginEditingNotification
  1985. didEndEditingNotificationName:UITextViewTextDidEndEditingNotification];
  1986. // Unregistering for orientation changes notification
  1987. #pragma clang diagnostic push
  1988. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1989. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillChangeStatusBarOrientationNotification object:[UIApplication sharedApplication]];
  1990. #pragma clang diagnostic pop
  1991. }
  1992. -(void)showLog:(NSString*)logString
  1993. {
  1994. [self showLog:logString indentation:0];
  1995. }
  1996. -(void)showLog:(NSString*)logString indentation:(NSInteger)indent
  1997. {
  1998. static NSInteger indentation = 0;
  1999. if (indent < 0)
  2000. {
  2001. indentation = MAX(0, indentation + indent);
  2002. }
  2003. if (_enableDebugging)
  2004. {
  2005. NSMutableString *preLog = [[NSMutableString alloc] init];
  2006. for (int i = 0; i<=indentation; i++) {
  2007. [preLog appendString:@"|\t"];
  2008. }
  2009. [preLog appendString:logString];
  2010. NSLog(@"%@",preLog);
  2011. }
  2012. if (indent > 0)
  2013. {
  2014. indentation += indent;
  2015. }
  2016. }
  2017. @end