IQKeyboardManager.m 104 KB

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