IQKeyboardManager.m 103 KB

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