IQKeyboardManager.swift 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277
  1. //
  2. // IQKeyboardManager.swift
  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 Foundation
  24. import CoreGraphics
  25. import UIKit
  26. import QuartzCore
  27. ///---------------------
  28. // MARK: IQToolbar tags
  29. ///---------------------
  30. /**
  31. Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
  32. */
  33. @objc public class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
  34. /**
  35. Default tag for toolbar with Done button -1002.
  36. */
  37. private static let kIQDoneButtonToolbarTag = -1002
  38. /**
  39. Default tag for toolbar with Previous/Next buttons -1005.
  40. */
  41. private static let kIQPreviousNextButtonToolbarTag = -1005
  42. /**
  43. Invalid point value.
  44. */
  45. private static let kIQCGPointInvalid = CGPoint.init(x: CGFloat.greatestFiniteMagnitude, y: CGFloat.greatestFiniteMagnitude)
  46. ///---------------------------
  47. // MARK: UIKeyboard handling
  48. ///---------------------------
  49. /**
  50. Registered classes list with library.
  51. */
  52. private var registeredClasses = [UIView.Type]()
  53. /**
  54. Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
  55. */
  56. @objc public var enable = false {
  57. didSet {
  58. //If not enable, enable it.
  59. if enable == true &&
  60. oldValue == false {
  61. //If keyboard is currently showing. Sending a fake notification for keyboardWillHide to retain view's original position.
  62. if let notification = _kbShowNotification {
  63. keyboardWillShow(notification)
  64. }
  65. showLog("Enabled")
  66. } else if enable == false &&
  67. oldValue == true { //If not disable, desable it.
  68. keyboardWillHide(nil)
  69. showLog("Disabled")
  70. }
  71. }
  72. }
  73. private func privateIsEnabled() -> Bool {
  74. var isEnabled = enable
  75. // let enableMode = _textFieldView?.enableMode
  76. //
  77. // if enableMode == .enabled {
  78. // isEnabled = true
  79. // } else if enableMode == .disabled {
  80. // isEnabled = false
  81. // } else {
  82. if let textFieldViewController = _textFieldView?.viewContainingController() {
  83. if isEnabled == false {
  84. //If viewController is kind of enable viewController class, then assuming it's enabled.
  85. for enabledClass in enabledDistanceHandlingClasses {
  86. if textFieldViewController.isKind(of: enabledClass) {
  87. isEnabled = true
  88. break
  89. }
  90. }
  91. }
  92. if isEnabled == true {
  93. //If viewController is kind of disabled viewController class, then assuming it's disabled.
  94. for disabledClass in disabledDistanceHandlingClasses {
  95. if textFieldViewController.isKind(of: disabledClass) {
  96. isEnabled = false
  97. break
  98. }
  99. }
  100. //Special Controllers
  101. if isEnabled == true {
  102. let classNameString = NSStringFromClass(type(of: textFieldViewController.self))
  103. //_UIAlertControllerTextFieldViewController
  104. if classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController") {
  105. isEnabled = false
  106. }
  107. }
  108. }
  109. }
  110. // }
  111. return isEnabled
  112. }
  113. /**
  114. To set keyboard distance from textField. can't be less than zero. Default is 10.0.
  115. */
  116. @objc public var keyboardDistanceFromTextField: CGFloat {
  117. set {
  118. _privateKeyboardDistanceFromTextField = max(0, newValue)
  119. showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
  120. }
  121. get {
  122. return _privateKeyboardDistanceFromTextField
  123. }
  124. }
  125. /**
  126. Boolean to know if keyboard is showing.
  127. */
  128. @objc public var keyboardShowing: Bool {
  129. return _privateIsKeyboardShowing
  130. }
  131. /**
  132. moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
  133. */
  134. @objc public var movedDistance: CGFloat {
  135. return _privateMovedDistance
  136. }
  137. /**
  138. Returns the default singleton instance.
  139. */
  140. @objc public class var shared: IQKeyboardManager {
  141. struct Static {
  142. //Singleton instance. Initializing keyboard manger.
  143. static let kbManager = IQKeyboardManager()
  144. }
  145. /** @return Returns the default singleton instance. */
  146. return Static.kbManager
  147. }
  148. ///-------------------------
  149. // MARK: IQToolbar handling
  150. ///-------------------------
  151. /**
  152. Automatic add the IQToolbar functionality. Default is YES.
  153. */
  154. @objc public var enableAutoToolbar = true {
  155. didSet {
  156. privateIsEnableAutoToolbar() ? addToolbarIfRequired() : removeToolbarIfRequired()
  157. let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
  158. showLog("enableAutoToolbar: \(enableToolbar)")
  159. }
  160. }
  161. private func privateIsEnableAutoToolbar() -> Bool {
  162. var enableToolbar = enableAutoToolbar
  163. if let textFieldViewController = _textFieldView?.viewContainingController() {
  164. if enableToolbar == false {
  165. //If found any toolbar enabled classes then return.
  166. for enabledClass in enabledToolbarClasses {
  167. if textFieldViewController.isKind(of: enabledClass) {
  168. enableToolbar = true
  169. break
  170. }
  171. }
  172. }
  173. if enableToolbar == true {
  174. //If found any toolbar disabled classes then return.
  175. for disabledClass in disabledToolbarClasses {
  176. if textFieldViewController.isKind(of: disabledClass) {
  177. enableToolbar = false
  178. break
  179. }
  180. }
  181. //Special Controllers
  182. if enableToolbar == true {
  183. let classNameString = NSStringFromClass(type(of: textFieldViewController.self))
  184. //_UIAlertControllerTextFieldViewController
  185. if classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController") {
  186. enableToolbar = false
  187. }
  188. }
  189. }
  190. }
  191. return enableToolbar
  192. }
  193. /**
  194. /**
  195. IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view.
  196. IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's.
  197. IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate.
  198. Default is IQAutoToolbarBySubviews.
  199. */
  200. AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
  201. */
  202. @objc public var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
  203. /**
  204. If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
  205. */
  206. @objc public var shouldToolbarUsesTextFieldTintColor = false
  207. /**
  208. This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
  209. */
  210. @objc public var toolbarTintColor: UIColor?
  211. /**
  212. This is used for toolbar.barTintColor. Default is nil and uses white color.
  213. */
  214. @objc public var toolbarBarTintColor: UIColor?
  215. /**
  216. IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide.
  217. IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case.
  218. IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
  219. */
  220. @objc public var previousNextDisplayMode = IQPreviousNextDisplayMode.default
  221. /**
  222. Toolbar previous/next/done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
  223. */
  224. @objc public var toolbarPreviousBarButtonItemImage: UIImage?
  225. @objc public var toolbarNextBarButtonItemImage: UIImage?
  226. @objc public var toolbarDoneBarButtonItemImage: UIImage?
  227. /**
  228. Toolbar previous/next/done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
  229. */
  230. @objc public var toolbarPreviousBarButtonItemText: String?
  231. @objc public var toolbarNextBarButtonItemText: String?
  232. @objc public var toolbarDoneBarButtonItemText: String?
  233. /**
  234. If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
  235. */
  236. @objc public var shouldShowToolbarPlaceholder = true
  237. /**
  238. Placeholder Font. Default is nil.
  239. */
  240. @objc public var placeholderFont: UIFont?
  241. /**
  242. Placeholder Color. Default is nil. Which means lightGray
  243. */
  244. @objc public var placeholderColor: UIColor?
  245. /**
  246. Placeholder Button Color when it's treated as button. Default is nil. Which means iOS Blue for light toolbar and Yellow for dark toolbar
  247. */
  248. @objc public var placeholderButtonColor: UIColor?
  249. ///--------------------------
  250. // MARK: UITextView handling
  251. ///--------------------------
  252. /** used to adjust contentInset of UITextView. */
  253. private var startingTextViewContentInsets = UIEdgeInsets()
  254. /** used to adjust scrollIndicatorInsets of UITextView. */
  255. private var startingTextViewScrollIndicatorInsets = UIEdgeInsets()
  256. /** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
  257. private var isTextViewContentInsetChanged = false
  258. ///---------------------------------------
  259. // MARK: UIKeyboard appearance overriding
  260. ///---------------------------------------
  261. /**
  262. Override the keyboardAppearance for all textField/textView. Default is NO.
  263. */
  264. @objc public var overrideKeyboardAppearance = false
  265. /**
  266. If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
  267. */
  268. @objc public var keyboardAppearance = UIKeyboardAppearance.default
  269. ///-----------------------------------------------------------
  270. // MARK: UITextField/UITextView Next/Previous/Resign handling
  271. ///-----------------------------------------------------------
  272. /**
  273. Resigns Keyboard on touching outside of UITextField/View. Default is NO.
  274. */
  275. @objc public var shouldResignOnTouchOutside = false {
  276. didSet {
  277. resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
  278. let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
  279. showLog("shouldResignOnTouchOutside: \(shouldResign)")
  280. }
  281. }
  282. /** 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 */
  283. @objc lazy public var resignFirstResponderGesture: UITapGestureRecognizer = {
  284. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
  285. tapGesture.cancelsTouchesInView = false
  286. tapGesture.delegate = self
  287. return tapGesture
  288. }()
  289. /*******************************************/
  290. private func privateShouldResignOnTouchOutside() -> Bool {
  291. var shouldResign = shouldResignOnTouchOutside
  292. let enableMode = _textFieldView?.shouldResignOnTouchOutsideMode
  293. if enableMode == .enabled {
  294. shouldResign = true
  295. } else if enableMode == .disabled {
  296. shouldResign = false
  297. } else {
  298. if let textFieldViewController = _textFieldView?.viewContainingController() {
  299. if shouldResign == false {
  300. //If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
  301. for enabledClass in enabledTouchResignedClasses {
  302. if textFieldViewController.isKind(of: enabledClass) {
  303. shouldResign = true
  304. break
  305. }
  306. }
  307. }
  308. if shouldResign == true {
  309. //If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
  310. for disabledClass in disabledTouchResignedClasses {
  311. if textFieldViewController.isKind(of: disabledClass) {
  312. shouldResign = false
  313. break
  314. }
  315. }
  316. //Special Controllers
  317. if shouldResign == true {
  318. let classNameString = NSStringFromClass(type(of: textFieldViewController.self))
  319. //_UIAlertControllerTextFieldViewController
  320. if classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController") {
  321. shouldResign = false
  322. }
  323. }
  324. }
  325. }
  326. }
  327. return shouldResign
  328. }
  329. /**
  330. Resigns currently first responder field.
  331. */
  332. @objc @discardableResult public func resignFirstResponder() -> Bool {
  333. if let textFieldRetain = _textFieldView {
  334. //Resigning first responder
  335. let isResignFirstResponder = textFieldRetain.resignFirstResponder()
  336. // If it refuses then becoming it as first responder again. (Bug ID: #96)
  337. if isResignFirstResponder == false {
  338. //If it refuses to resign then becoming it first responder again for getting notifications callback.
  339. textFieldRetain.becomeFirstResponder()
  340. showLog("Refuses to resign first responder: \(textFieldRetain)")
  341. }
  342. return isResignFirstResponder
  343. }
  344. return false
  345. }
  346. /**
  347. Returns YES if can navigate to previous responder textField/textView, otherwise NO.
  348. */
  349. @objc public var canGoPrevious: Bool {
  350. //Getting all responder view's.
  351. if let textFields = responderViews() {
  352. if let textFieldRetain = _textFieldView {
  353. //Getting index of current textField.
  354. if let index = textFields.firstIndex(of: textFieldRetain) {
  355. //If it is not first textField. then it's previous object canBecomeFirstResponder.
  356. if index > 0 {
  357. return true
  358. }
  359. }
  360. }
  361. }
  362. return false
  363. }
  364. /**
  365. Returns YES if can navigate to next responder textField/textView, otherwise NO.
  366. */
  367. @objc public var canGoNext: Bool {
  368. //Getting all responder view's.
  369. if let textFields = responderViews() {
  370. if let textFieldRetain = _textFieldView {
  371. //Getting index of current textField.
  372. if let index = textFields.firstIndex(of: textFieldRetain) {
  373. //If it is not first textField. then it's previous object canBecomeFirstResponder.
  374. if index < textFields.count-1 {
  375. return true
  376. }
  377. }
  378. }
  379. }
  380. return false
  381. }
  382. /**
  383. Navigate to previous responder textField/textView.
  384. */
  385. @objc @discardableResult public func goPrevious() -> Bool {
  386. //Getting all responder view's.
  387. if let textFieldRetain = _textFieldView {
  388. if let textFields = responderViews() {
  389. //Getting index of current textField.
  390. if let index = textFields.firstIndex(of: textFieldRetain) {
  391. //If it is not first textField. then it's previous object becomeFirstResponder.
  392. if index > 0 {
  393. let nextTextField = textFields[index-1]
  394. let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
  395. // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
  396. if isAcceptAsFirstResponder == false {
  397. //If next field refuses to become first responder then restoring old textField as first responder.
  398. textFieldRetain.becomeFirstResponder()
  399. showLog("Refuses to become first responder: \(nextTextField)")
  400. }
  401. return isAcceptAsFirstResponder
  402. }
  403. }
  404. }
  405. }
  406. return false
  407. }
  408. /**
  409. Navigate to next responder textField/textView.
  410. */
  411. @objc @discardableResult public func goNext() -> Bool {
  412. //Getting all responder view's.
  413. if let textFieldRetain = _textFieldView {
  414. if let textFields = responderViews() {
  415. //Getting index of current textField.
  416. if let index = textFields.firstIndex(of: textFieldRetain) {
  417. //If it is not last textField. then it's next object becomeFirstResponder.
  418. if index < textFields.count-1 {
  419. let nextTextField = textFields[index+1]
  420. let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
  421. // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
  422. if isAcceptAsFirstResponder == false {
  423. //If next field refuses to become first responder then restoring old textField as first responder.
  424. textFieldRetain.becomeFirstResponder()
  425. showLog("Refuses to become first responder: \(nextTextField)")
  426. }
  427. return isAcceptAsFirstResponder
  428. }
  429. }
  430. }
  431. }
  432. return false
  433. }
  434. /** previousAction. */
  435. @objc internal func previousAction (_ barButton: IQBarButtonItem) {
  436. //If user wants to play input Click sound.
  437. if shouldPlayInputClicks == true {
  438. //Play Input Click Sound.
  439. UIDevice.current.playInputClick()
  440. }
  441. if canGoPrevious == true {
  442. if let textFieldRetain = _textFieldView {
  443. let isAcceptAsFirstResponder = goPrevious()
  444. var invocation = barButton.invocation
  445. var sender = textFieldRetain
  446. //Handling search bar special case
  447. do {
  448. if let searchBar = textFieldRetain.textFieldSearchBar() {
  449. invocation = searchBar.keyboardToolbar.previousBarButton.invocation
  450. sender = searchBar
  451. }
  452. }
  453. if isAcceptAsFirstResponder {
  454. invocation?.invoke(from: sender)
  455. }
  456. }
  457. }
  458. }
  459. /** nextAction. */
  460. @objc internal func nextAction (_ barButton: IQBarButtonItem) {
  461. //If user wants to play input Click sound.
  462. if shouldPlayInputClicks == true {
  463. //Play Input Click Sound.
  464. UIDevice.current.playInputClick()
  465. }
  466. if canGoNext == true {
  467. if let textFieldRetain = _textFieldView {
  468. let isAcceptAsFirstResponder = goNext()
  469. var invocation = barButton.invocation
  470. var sender = textFieldRetain
  471. //Handling search bar special case
  472. do {
  473. if let searchBar = textFieldRetain.textFieldSearchBar() {
  474. invocation = searchBar.keyboardToolbar.nextBarButton.invocation
  475. sender = searchBar
  476. }
  477. }
  478. if isAcceptAsFirstResponder {
  479. invocation?.invoke(from: sender)
  480. }
  481. }
  482. }
  483. }
  484. /** doneAction. Resigning current textField. */
  485. @objc internal func doneAction (_ barButton: IQBarButtonItem) {
  486. //If user wants to play input Click sound.
  487. if shouldPlayInputClicks == true {
  488. //Play Input Click Sound.
  489. UIDevice.current.playInputClick()
  490. }
  491. if let textFieldRetain = _textFieldView {
  492. //Resign textFieldView.
  493. let isResignedFirstResponder = resignFirstResponder()
  494. var invocation = barButton.invocation
  495. var sender = textFieldRetain
  496. //Handling search bar special case
  497. do {
  498. if let searchBar = textFieldRetain.textFieldSearchBar() {
  499. invocation = searchBar.keyboardToolbar.doneBarButton.invocation
  500. sender = searchBar
  501. }
  502. }
  503. if isResignedFirstResponder {
  504. invocation?.invoke(from: sender)
  505. }
  506. }
  507. }
  508. /** Resigning on tap gesture. (Enhancement ID: #14)*/
  509. @objc internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
  510. if gesture.state == .ended {
  511. //Resigning currently responder textField.
  512. resignFirstResponder()
  513. }
  514. }
  515. /** 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. */
  516. @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  517. return false
  518. }
  519. /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
  520. @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
  521. // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
  522. for ignoreClass in touchResignedGestureIgnoreClasses {
  523. if touch.view?.isKind(of: ignoreClass) == true {
  524. return false
  525. }
  526. }
  527. return true
  528. }
  529. ///-----------------------
  530. // MARK: UISound handling
  531. ///-----------------------
  532. /**
  533. If YES, then it plays inputClick sound on next/previous/done click.
  534. */
  535. @objc public var shouldPlayInputClicks = true
  536. ///---------------------------
  537. // MARK: UIAnimation handling
  538. ///---------------------------
  539. /**
  540. If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
  541. */
  542. @objc public var layoutIfNeededOnUpdate = false
  543. ///------------------------------------
  544. // MARK: Class Level disabling methods
  545. ///------------------------------------
  546. /**
  547. Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
  548. */
  549. @objc public var disabledDistanceHandlingClasses = [UIViewController.Type]()
  550. /**
  551. Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
  552. */
  553. @objc public var enabledDistanceHandlingClasses = [UIViewController.Type]()
  554. /**
  555. Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
  556. */
  557. @objc public var disabledToolbarClasses = [UIViewController.Type]()
  558. /**
  559. Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
  560. */
  561. @objc public var enabledToolbarClasses = [UIViewController.Type]()
  562. /**
  563. Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
  564. */
  565. @objc public var toolbarPreviousNextAllowedClasses = [UIView.Type]()
  566. /**
  567. Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
  568. */
  569. @objc public var disabledTouchResignedClasses = [UIViewController.Type]()
  570. /**
  571. Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
  572. */
  573. @objc public var enabledTouchResignedClasses = [UIViewController.Type]()
  574. /**
  575. if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar]
  576. */
  577. @objc public var touchResignedGestureIgnoreClasses = [UIView.Type]()
  578. ///----------------------------------
  579. // MARK: Third Party Library support
  580. /// Add TextField/TextView Notifications customised Notifications. For example while using YYTextView https://github.com/ibireme/YYText
  581. ///----------------------------------
  582. /**
  583. Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the Notification object must be idential to UITextField/UITextView Notification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
  584. @param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
  585. @param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
  586. */
  587. @objc public func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName: String, didEndEditingNotificationName: String) {
  588. registeredClasses.append(aClass)
  589. NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: Notification.Name(rawValue: didBeginEditingNotificationName), object: nil)
  590. NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: Notification.Name(rawValue: didEndEditingNotificationName), object: nil)
  591. }
  592. @objc public func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName: String, didEndEditingNotificationName: String) {
  593. if let index = registeredClasses.firstIndex(where: { element in
  594. return element == aClass.self
  595. }) {
  596. registeredClasses.remove(at: index)
  597. }
  598. NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: didBeginEditingNotificationName), object: nil)
  599. NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: didEndEditingNotificationName), object: nil)
  600. }
  601. /**************************************************************************************/
  602. ///------------------------
  603. // MARK: Private variables
  604. ///------------------------
  605. /*******************************************/
  606. /** To save UITextField/UITextView object voa textField/textView notifications. */
  607. private weak var _textFieldView: UIView?
  608. /** To save rootViewController.view.frame.origin. */
  609. private var _topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
  610. /** To overcome with popGestureRecognizer issue Bug ID: #1361 */
  611. private weak var _rootViewControllerWhilePopGestureRecognizerActive: UIViewController?
  612. private var _topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
  613. /** To save rootViewController */
  614. private weak var _rootViewController: UIViewController?
  615. /*******************************************/
  616. /** Variable to save lastScrollView that was scrolled. */
  617. private weak var _lastScrollView: UIScrollView?
  618. /** LastScrollView's initial contentOffset. */
  619. private var _startingContentOffset = CGPoint.zero
  620. /** LastScrollView's initial scrollIndicatorInsets. */
  621. private var _startingScrollIndicatorInsets = UIEdgeInsets()
  622. /** LastScrollView's initial contentInsets. */
  623. private var _startingContentInsets = UIEdgeInsets()
  624. /*******************************************/
  625. /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
  626. private var _kbShowNotification: Notification?
  627. /** To save keyboard rame. */
  628. private var _kbFrame = CGRect.zero
  629. /** To save keyboard animation duration. */
  630. private var _animationDuration: TimeInterval = 0.25
  631. /** To mimic the keyboard animation */
  632. #if swift(>=4.2)
  633. private var _animationCurve: UIView.AnimationOptions = .curveEaseOut
  634. #else
  635. private var _animationCurve: UIViewAnimationOptions = .curveEaseOut
  636. #endif
  637. /*******************************************/
  638. /** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
  639. private var _privateIsKeyboardShowing = false
  640. private var _privateMovedDistance: CGFloat = 0.0
  641. /** To use with keyboardDistanceFromTextField. */
  642. private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
  643. /** To know if we have any pending request to adjust view position. */
  644. private var _privateHasPendingAdjustRequest = false
  645. /**************************************************************************************/
  646. ///--------------------------------------
  647. // MARK: Initialization/Deinitialization
  648. ///--------------------------------------
  649. /* Singleton Object Initialization. */
  650. override init() {
  651. super.init()
  652. self.registerAllNotifications()
  653. //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
  654. resignFirstResponderGesture.isEnabled = shouldResignOnTouchOutside
  655. //Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550)
  656. //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
  657. let textField = UITextField()
  658. textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
  659. textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
  660. disabledDistanceHandlingClasses.append(UITableViewController.self)
  661. disabledDistanceHandlingClasses.append(UIAlertController.self)
  662. disabledToolbarClasses.append(UIAlertController.self)
  663. disabledTouchResignedClasses.append(UIAlertController.self)
  664. toolbarPreviousNextAllowedClasses.append(UITableView.self)
  665. toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
  666. toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
  667. touchResignedGestureIgnoreClasses.append(UIControl.self)
  668. touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
  669. }
  670. /** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
  671. /** It doesn't work from Swift 1.2 */
  672. // override public class func load() {
  673. // super.load()
  674. //
  675. // //Enabling IQKeyboardManager.
  676. // IQKeyboardManager.shared.enable = true
  677. // }
  678. deinit {
  679. // Disable the keyboard manager.
  680. enable = false
  681. //Removing notification observers on dealloc.
  682. NotificationCenter.default.removeObserver(self)
  683. }
  684. /** Getting keyWindow. */
  685. private func keyWindow() -> UIWindow? {
  686. if let keyWindow = _textFieldView?.window {
  687. return keyWindow
  688. } else {
  689. struct Static {
  690. /** @abstract Save keyWindow object for reuse.
  691. @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
  692. static weak var keyWindow: UIWindow?
  693. }
  694. //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
  695. if let originalKeyWindow = UIApplication.shared.keyWindow,
  696. (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
  697. Static.keyWindow = originalKeyWindow
  698. }
  699. //Return KeyWindow
  700. return Static.keyWindow
  701. }
  702. }
  703. ///-----------------------
  704. // MARK: Helper Functions
  705. ///-----------------------
  706. private func optimizedAdjustPosition() {
  707. if _privateHasPendingAdjustRequest == false {
  708. _privateHasPendingAdjustRequest = true
  709. OperationQueue.main.addOperation {
  710. self.adjustPosition()
  711. self._privateHasPendingAdjustRequest = false
  712. }
  713. }
  714. }
  715. /* Adjusting RootViewController's frame according to interface orientation. */
  716. private func adjustPosition() {
  717. // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
  718. if _privateHasPendingAdjustRequest == true,
  719. let textFieldView = _textFieldView,
  720. let rootController = textFieldView.parentContainerViewController(),
  721. let window = keyWindow(),
  722. let textFieldViewRectInWindow = textFieldView.superview?.convert(textFieldView.frame, to: window),
  723. let textFieldViewRectInRootSuperview = textFieldView.superview?.convert(textFieldView.frame, to: rootController.view?.superview) {
  724. let startTime = CACurrentMediaTime()
  725. showLog("****** \(#function) started ******", indentation: 1)
  726. // Getting RootViewOrigin.
  727. var rootViewOrigin = rootController.view.frame.origin
  728. //Maintain keyboardDistanceFromTextField
  729. var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
  730. if let searchBar = textFieldView.textFieldSearchBar() {
  731. specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
  732. }
  733. let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
  734. var kbSize = _kbFrame.size
  735. do {
  736. var kbFrame = _kbFrame
  737. kbFrame.origin.y -= newKeyboardDistanceFromTextField
  738. kbFrame.size.height += newKeyboardDistanceFromTextField
  739. //Calculating actual keyboard covered size respect to window, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) (Bug ID: #1506)
  740. let intersectRect = kbFrame.intersection(window.frame)
  741. if intersectRect.isNull {
  742. kbSize = CGSize(width: kbFrame.size.width, height: 0)
  743. } else {
  744. kbSize = intersectRect.size
  745. }
  746. }
  747. let statusBarHeight: CGFloat
  748. #if swift(>=5.1)
  749. if #available(iOS 13, *) {
  750. statusBarHeight = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
  751. } else {
  752. statusBarHeight = UIApplication.shared.statusBarFrame.height
  753. }
  754. #else
  755. statusBarHeight = UIApplication.shared.statusBarFrame.height
  756. #endif
  757. let navigationBarAreaHeight: CGFloat = statusBarHeight + ( rootController.navigationController?.navigationBar.frame.height ?? 0)
  758. let layoutAreaHeight: CGFloat = rootController.view.layoutMargins.bottom
  759. let topLayoutGuide: CGFloat = max(navigationBarAreaHeight, layoutAreaHeight) + 5
  760. let bottomLayoutGuide: CGFloat = (textFieldView is UITextView) ? 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.
  761. // Move positive = textField is hidden.
  762. // Move negative = textField is showing.
  763. // Calculating move position.
  764. var move: CGFloat = min(textFieldViewRectInRootSuperview.minY-(topLayoutGuide), textFieldViewRectInWindow.maxY-(window.frame.height-kbSize.height)+bottomLayoutGuide)
  765. showLog("Need to move: \(move)")
  766. var superScrollView: UIScrollView?
  767. var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
  768. //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
  769. while let view = superView {
  770. if view.isScrollEnabled && view.shouldIgnoreScrollingAdjustment == false {
  771. superScrollView = view
  772. break
  773. } else {
  774. // Getting it's superScrollView. // (Enhancement ID: #21, #24)
  775. superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
  776. }
  777. }
  778. //If there was a lastScrollView. // (Bug ID: #34)
  779. if let lastScrollView = _lastScrollView {
  780. //If we can't find current superScrollView, then setting lastScrollView to it's original form.
  781. if superScrollView == nil {
  782. if lastScrollView.contentInset != self._startingContentInsets {
  783. showLog("Restoring contentInset to: \(_startingContentInsets)")
  784. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  785. lastScrollView.contentInset = self._startingContentInsets
  786. lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
  787. })
  788. }
  789. if lastScrollView.shouldRestoreScrollViewContentOffset == true && lastScrollView.contentOffset.equalTo(_startingContentOffset) == false {
  790. showLog("Restoring contentOffset to: \(_startingContentOffset)")
  791. var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
  792. if #available(iOS 9, *) {
  793. animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil
  794. }
  795. if animatedContentOffset {
  796. lastScrollView.setContentOffset(_startingContentOffset, animated: UIView.areAnimationsEnabled)
  797. } else {
  798. lastScrollView.contentOffset = _startingContentOffset
  799. }
  800. }
  801. _startingContentInsets = UIEdgeInsets()
  802. _startingScrollIndicatorInsets = UIEdgeInsets()
  803. _startingContentOffset = CGPoint.zero
  804. _lastScrollView = nil
  805. } else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
  806. if lastScrollView.contentInset != self._startingContentInsets {
  807. showLog("Restoring contentInset to: \(_startingContentInsets)")
  808. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  809. lastScrollView.contentInset = self._startingContentInsets
  810. lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
  811. })
  812. }
  813. if lastScrollView.shouldRestoreScrollViewContentOffset == true && lastScrollView.contentOffset.equalTo(_startingContentOffset) == false {
  814. showLog("Restoring contentOffset to: \(_startingContentOffset)")
  815. var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
  816. if #available(iOS 9, *) {
  817. animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil
  818. }
  819. if animatedContentOffset {
  820. lastScrollView.setContentOffset(_startingContentOffset, animated: UIView.areAnimationsEnabled)
  821. } else {
  822. lastScrollView.contentOffset = _startingContentOffset
  823. }
  824. }
  825. _lastScrollView = superScrollView
  826. if let scrollView = superScrollView {
  827. _startingContentInsets = scrollView.contentInset
  828. _startingContentOffset = scrollView.contentOffset
  829. #if swift(>=5.1)
  830. if #available(iOS 11.1, *) {
  831. _startingScrollIndicatorInsets = scrollView.verticalScrollIndicatorInsets
  832. } else {
  833. _startingScrollIndicatorInsets = scrollView.scrollIndicatorInsets
  834. }
  835. #else
  836. _startingScrollIndicatorInsets = scrollView.scrollIndicatorInsets
  837. #endif
  838. }
  839. showLog("Saving ScrollView New contentInset: \(_startingContentInsets) and contentOffset: \(_startingContentOffset)")
  840. }
  841. //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
  842. } else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
  843. _lastScrollView = unwrappedSuperScrollView
  844. _startingContentInsets = unwrappedSuperScrollView.contentInset
  845. _startingContentOffset = unwrappedSuperScrollView.contentOffset
  846. #if swift(>=5.1)
  847. if #available(iOS 11.1, *) {
  848. _startingScrollIndicatorInsets = unwrappedSuperScrollView.verticalScrollIndicatorInsets
  849. } else {
  850. _startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
  851. }
  852. #else
  853. _startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
  854. #endif
  855. showLog("Saving ScrollView contentInset: \(_startingContentInsets) and contentOffset: \(_startingContentOffset)")
  856. }
  857. // Special case for ScrollView.
  858. // If we found lastScrollView then setting it's contentOffset to show textField.
  859. if let lastScrollView = _lastScrollView {
  860. //Saving
  861. var lastView = textFieldView
  862. var superScrollView = _lastScrollView
  863. while let scrollView = superScrollView {
  864. var shouldContinue = false
  865. if move > 0 {
  866. shouldContinue = move > (-scrollView.contentOffset.y - scrollView.contentInset.top)
  867. } else if let tableView = scrollView.superviewOfClassType(UITableView.self) as? UITableView {
  868. shouldContinue = scrollView.contentOffset.y > 0
  869. if shouldContinue == true, let tableCell = textFieldView.superviewOfClassType(UITableViewCell.self) as? UITableViewCell, let indexPath = tableView.indexPath(for: tableCell), let previousIndexPath = tableView.previousIndexPath(of: indexPath) {
  870. let previousCellRect = tableView.rectForRow(at: previousIndexPath)
  871. if previousCellRect.isEmpty == false {
  872. let previousCellRectInRootSuperview = tableView.convert(previousCellRect, to: rootController.view.superview)
  873. move = min(0, previousCellRectInRootSuperview.maxY - topLayoutGuide)
  874. }
  875. }
  876. } else if let collectionView = scrollView.superviewOfClassType(UICollectionView.self) as? UICollectionView {
  877. shouldContinue = scrollView.contentOffset.y > 0
  878. if shouldContinue == true, let collectionCell = textFieldView.superviewOfClassType(UICollectionViewCell.self) as? UICollectionViewCell, let indexPath = collectionView.indexPath(for: collectionCell), let previousIndexPath = collectionView.previousIndexPath(of: indexPath), let attributes = collectionView.layoutAttributesForItem(at: previousIndexPath) {
  879. let previousCellRect = attributes.frame
  880. if previousCellRect.isEmpty == false {
  881. let previousCellRectInRootSuperview = collectionView.convert(previousCellRect, to: rootController.view.superview)
  882. move = min(0, previousCellRectInRootSuperview.maxY - topLayoutGuide)
  883. }
  884. }
  885. } else {
  886. shouldContinue = textFieldViewRectInRootSuperview.origin.y < topLayoutGuide
  887. if shouldContinue {
  888. move = min(0, textFieldViewRectInRootSuperview.origin.y - topLayoutGuide)
  889. }
  890. }
  891. //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
  892. if shouldContinue {
  893. var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
  894. var nextScrollView: UIScrollView?
  895. while let view = tempScrollView {
  896. if view.isScrollEnabled && view.shouldIgnoreScrollingAdjustment == false {
  897. nextScrollView = view
  898. break
  899. } else {
  900. tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
  901. }
  902. }
  903. //Getting lastViewRect.
  904. if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
  905. //Calculating the expected Y offset from move and scrollView's contentOffset.
  906. var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y, -move)
  907. //Rearranging the expected Y offset according to the view.
  908. shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y)
  909. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
  910. //nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
  911. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
  912. //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
  913. if textFieldView is UITextView == true &&
  914. nextScrollView == nil &&
  915. shouldOffsetY >= 0 {
  916. // Converting Rectangle according to window bounds.
  917. if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
  918. //Calculating expected fix distance which needs to be managed from navigation bar
  919. let expectedFixDistance = currentTextFieldViewRect.minY - topLayoutGuide
  920. //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)
  921. shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
  922. //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
  923. move = 0
  924. } else {
  925. //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
  926. move -= (shouldOffsetY-scrollView.contentOffset.y)
  927. }
  928. } else {
  929. //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
  930. move -= (shouldOffsetY-scrollView.contentOffset.y)
  931. }
  932. let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
  933. if scrollView.contentOffset.equalTo(newContentOffset) == false {
  934. showLog("old contentOffset: \(scrollView.contentOffset) new contentOffset: \(newContentOffset)")
  935. self.showLog("Remaining Move: \(move)")
  936. //Getting problem while using `setContentOffset:animated:`, So I used animation API.
  937. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  938. var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
  939. if #available(iOS 9, *) {
  940. animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil
  941. }
  942. if animatedContentOffset {
  943. scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
  944. } else {
  945. scrollView.contentOffset = newContentOffset
  946. }
  947. }) { _ in
  948. if scrollView is UITableView || scrollView is UICollectionView {
  949. //This will update the next/previous states
  950. self.addToolbarIfRequired()
  951. }
  952. }
  953. }
  954. }
  955. // Getting next lastView & superScrollView.
  956. lastView = scrollView
  957. superScrollView = nextScrollView
  958. } else {
  959. move = 0
  960. break
  961. }
  962. }
  963. //Updating contentInset
  964. if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) {
  965. let bottom: CGFloat = (kbSize.height-newKeyboardDistanceFromTextField)-(window.frame.height-lastScrollViewRect.maxY)
  966. // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
  967. var movedInsets = lastScrollView.contentInset
  968. movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
  969. if lastScrollView.contentInset != movedInsets {
  970. showLog("old ContentInset: \(lastScrollView.contentInset) new ContentInset: \(movedInsets)")
  971. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  972. lastScrollView.contentInset = movedInsets
  973. var newInset: UIEdgeInsets
  974. #if swift(>=5.1)
  975. if #available(iOS 11.1, *) {
  976. newInset = lastScrollView.verticalScrollIndicatorInsets
  977. } else {
  978. newInset = lastScrollView.scrollIndicatorInsets
  979. }
  980. #else
  981. newInset = lastScrollView.scrollIndicatorInsets
  982. #endif
  983. newInset.bottom = movedInsets.bottom
  984. lastScrollView.scrollIndicatorInsets = newInset
  985. })
  986. }
  987. }
  988. }
  989. //Going ahead. No else if.
  990. //Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
  991. //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
  992. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
  993. if let textView = textFieldView as? UITextView {
  994. // CGRect rootSuperViewFrameInWindow = [_rootViewController.view.superview convertRect:_rootViewController.view.superview.bounds toView:keyWindow];
  995. //
  996. // CGFloat keyboardOverlapping = CGRectGetMaxY(rootSuperViewFrameInWindow) - keyboardYPosition;
  997. //
  998. // CGFloat textViewHeight = MIN(CGRectGetHeight(_textFieldView.frame), (CGRectGetHeight(rootSuperViewFrameInWindow)-topLayoutGuide-keyboardOverlapping));
  999. let keyboardYPosition = window.frame.height - (kbSize.height-newKeyboardDistanceFromTextField)
  1000. var rootSuperViewFrameInWindow = window.frame
  1001. if let rootSuperview = rootController.view.superview {
  1002. rootSuperViewFrameInWindow = rootSuperview.convert(rootSuperview.bounds, to: window)
  1003. }
  1004. let keyboardOverlapping = rootSuperViewFrameInWindow.maxY - keyboardYPosition
  1005. let textViewHeight = min(textView.frame.height, rootSuperViewFrameInWindow.height-topLayoutGuide-keyboardOverlapping)
  1006. if textView.frame.size.height-textView.contentInset.bottom>textViewHeight {
  1007. //_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
  1008. if self.isTextViewContentInsetChanged == false {
  1009. self.startingTextViewContentInsets = textView.contentInset
  1010. #if swift(>=5.1)
  1011. if #available(iOS 11.1, *) {
  1012. self.startingTextViewScrollIndicatorInsets = textView.verticalScrollIndicatorInsets
  1013. } else {
  1014. self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
  1015. }
  1016. #else
  1017. self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
  1018. #endif
  1019. }
  1020. self.isTextViewContentInsetChanged = true
  1021. var newContentInset = textView.contentInset
  1022. newContentInset.bottom = textView.frame.size.height-textViewHeight
  1023. if textView.contentInset != newContentInset {
  1024. self.showLog("\(textFieldView) Old UITextView.contentInset: \(textView.contentInset) New UITextView.contentInset: \(newContentInset)")
  1025. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1026. textView.contentInset = newContentInset
  1027. textView.scrollIndicatorInsets = newContentInset
  1028. }, completion: { (_) -> Void in })
  1029. }
  1030. }
  1031. }
  1032. // +Positive or zero.
  1033. if move >= 0 {
  1034. rootViewOrigin.y = max(rootViewOrigin.y - move, min(0, -(kbSize.height-newKeyboardDistanceFromTextField)))
  1035. if rootController.view.frame.origin.equalTo(rootViewOrigin) == false {
  1036. showLog("Moving Upward")
  1037. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1038. var rect = rootController.view.frame
  1039. rect.origin = rootViewOrigin
  1040. rootController.view.frame = rect
  1041. //Animating content if needed (Bug ID: #204)
  1042. if self.layoutIfNeededOnUpdate == true {
  1043. //Animating content (Bug ID: #160)
  1044. rootController.view.setNeedsLayout()
  1045. rootController.view.layoutIfNeeded()
  1046. }
  1047. self.showLog("Set \(rootController) origin to: \(rootViewOrigin)")
  1048. })
  1049. }
  1050. _privateMovedDistance = (_topViewBeginOrigin.y-rootViewOrigin.y)
  1051. } else { // -Negative
  1052. let disturbDistance: CGFloat = rootViewOrigin.y-_topViewBeginOrigin.y
  1053. // disturbDistance Negative = frame disturbed.
  1054. // disturbDistance positive = frame not disturbed.
  1055. if disturbDistance <= 0 {
  1056. rootViewOrigin.y -= max(move, disturbDistance)
  1057. if rootController.view.frame.origin.equalTo(rootViewOrigin) == false {
  1058. showLog("Moving Downward")
  1059. // Setting adjusted rootViewRect
  1060. // Setting adjusted rootViewRect
  1061. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1062. var rect = rootController.view.frame
  1063. rect.origin = rootViewOrigin
  1064. rootController.view.frame = rect
  1065. //Animating content if needed (Bug ID: #204)
  1066. if self.layoutIfNeededOnUpdate == true {
  1067. //Animating content (Bug ID: #160)
  1068. rootController.view.setNeedsLayout()
  1069. rootController.view.layoutIfNeeded()
  1070. }
  1071. self.showLog("Set \(rootController) origin to: \(rootViewOrigin)")
  1072. })
  1073. }
  1074. _privateMovedDistance = (_topViewBeginOrigin.y-rootViewOrigin.y)
  1075. }
  1076. }
  1077. let elapsedTime = CACurrentMediaTime() - startTime
  1078. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1079. }
  1080. }
  1081. private func restorePosition() {
  1082. _privateHasPendingAdjustRequest = false
  1083. // Setting rootViewController frame to it's original position. // (Bug ID: #18)
  1084. if _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == false {
  1085. if let rootViewController = _rootViewController {
  1086. if rootViewController.view.frame.origin.equalTo(self._topViewBeginOrigin) == false {
  1087. //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
  1088. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1089. self.showLog("Restoring \(rootViewController) origin to: \(self._topViewBeginOrigin)")
  1090. // Setting it's new frame
  1091. var rect = rootViewController.view.frame
  1092. rect.origin = self._topViewBeginOrigin
  1093. rootViewController.view.frame = rect
  1094. //Animating content if needed (Bug ID: #204)
  1095. if self.layoutIfNeededOnUpdate == true {
  1096. //Animating content (Bug ID: #160)
  1097. rootViewController.view.setNeedsLayout()
  1098. rootViewController.view.layoutIfNeeded()
  1099. }
  1100. })
  1101. }
  1102. self._privateMovedDistance = 0
  1103. if rootViewController.navigationController?.interactivePopGestureRecognizer?.state == .began {
  1104. self._rootViewControllerWhilePopGestureRecognizerActive = rootViewController
  1105. self._topViewBeginOriginWhilePopGestureRecognizerActive = self._topViewBeginOrigin
  1106. }
  1107. _rootViewController = nil
  1108. }
  1109. }
  1110. }
  1111. ///---------------------
  1112. // MARK: Public Methods
  1113. ///---------------------
  1114. /* Refreshes textField/textView position if any external changes is explicitly made by user. */
  1115. @objc public func reloadLayoutIfNeeded() {
  1116. if privateIsEnabled() == true {
  1117. if _privateIsKeyboardShowing == true,
  1118. _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == false,
  1119. let textFieldView = _textFieldView,
  1120. textFieldView.isAlertViewTextField() == false {
  1121. optimizedAdjustPosition()
  1122. }
  1123. }
  1124. }
  1125. ///-------------------------------
  1126. // MARK: UIKeyboard Notifications
  1127. ///-------------------------------
  1128. /* UIKeyboardWillShowNotification. */
  1129. @objc internal func keyboardWillShow(_ notification: Notification?) {
  1130. _kbShowNotification = notification
  1131. // Boolean to know keyboard is showing/hiding
  1132. _privateIsKeyboardShowing = true
  1133. let oldKBFrame = _kbFrame
  1134. if let info = notification?.userInfo {
  1135. #if swift(>=4.2)
  1136. let curveUserInfoKey = UIResponder.keyboardAnimationCurveUserInfoKey
  1137. let durationUserInfoKey = UIResponder.keyboardAnimationDurationUserInfoKey
  1138. let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
  1139. #else
  1140. let curveUserInfoKey = UIKeyboardAnimationCurveUserInfoKey
  1141. let durationUserInfoKey = UIKeyboardAnimationDurationUserInfoKey
  1142. let frameEndUserInfoKey = UIKeyboardFrameEndUserInfoKey
  1143. #endif
  1144. // Getting keyboard animation.
  1145. if let curve = info[curveUserInfoKey] as? UInt {
  1146. _animationCurve = .init(rawValue: curve)
  1147. } else {
  1148. _animationCurve = .curveEaseOut
  1149. }
  1150. // Getting keyboard animation duration
  1151. if let duration = info[durationUserInfoKey] as? TimeInterval {
  1152. //Saving animation duration
  1153. if duration != 0.0 {
  1154. _animationDuration = duration
  1155. }
  1156. } else {
  1157. _animationDuration = 0.25
  1158. }
  1159. // Getting UIKeyboardSize.
  1160. if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
  1161. _kbFrame = kbFrame
  1162. showLog("UIKeyboard Frame: \(_kbFrame)")
  1163. }
  1164. }
  1165. if privateIsEnabled() == false {
  1166. return
  1167. }
  1168. let startTime = CACurrentMediaTime()
  1169. showLog("****** \(#function) started ******", indentation: 1)
  1170. // (Bug ID: #5)
  1171. if let textFieldView = _textFieldView, _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == true {
  1172. // keyboard is not showing(At the beginning only). We should save rootViewRect.
  1173. _rootViewController = textFieldView.parentContainerViewController()
  1174. if let controller = _rootViewController {
  1175. if _rootViewControllerWhilePopGestureRecognizerActive == controller {
  1176. _topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive
  1177. } else {
  1178. _topViewBeginOrigin = controller.view.frame.origin
  1179. }
  1180. _rootViewControllerWhilePopGestureRecognizerActive = nil
  1181. _topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
  1182. self.showLog("Saving \(controller) beginning origin: \(self._topViewBeginOrigin)")
  1183. }
  1184. }
  1185. //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
  1186. if _kbFrame.equalTo(oldKBFrame) == false {
  1187. //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
  1188. if _privateIsKeyboardShowing == true,
  1189. let textFieldView = _textFieldView,
  1190. textFieldView.isAlertViewTextField() == false {
  1191. // keyboard is already showing. adjust position.
  1192. optimizedAdjustPosition()
  1193. }
  1194. }
  1195. let elapsedTime = CACurrentMediaTime() - startTime
  1196. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1197. }
  1198. /* UIKeyboardDidShowNotification. */
  1199. @objc internal func keyboardDidShow(_ notification: Notification?) {
  1200. if privateIsEnabled() == false {
  1201. return
  1202. }
  1203. let startTime = CACurrentMediaTime()
  1204. showLog("****** \(#function) started ******", indentation: 1)
  1205. if let textFieldView = _textFieldView,
  1206. let parentController = textFieldView.parentContainerViewController(), (parentController.modalPresentationStyle == UIModalPresentationStyle.formSheet || parentController.modalPresentationStyle == UIModalPresentationStyle.pageSheet),
  1207. textFieldView.isAlertViewTextField() == false {
  1208. self.optimizedAdjustPosition()
  1209. }
  1210. let elapsedTime = CACurrentMediaTime() - startTime
  1211. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1212. }
  1213. /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
  1214. @objc internal func keyboardWillHide(_ notification: Notification?) {
  1215. //If it's not a fake notification generated by [self setEnable:NO].
  1216. if notification != nil {
  1217. _kbShowNotification = nil
  1218. }
  1219. // Boolean to know keyboard is showing/hiding
  1220. _privateIsKeyboardShowing = false
  1221. if let info = notification?.userInfo {
  1222. #if swift(>=4.2)
  1223. let durationUserInfoKey = UIResponder.keyboardAnimationDurationUserInfoKey
  1224. #else
  1225. let durationUserInfoKey = UIKeyboardAnimationDurationUserInfoKey
  1226. #endif
  1227. // Getting keyboard animation duration
  1228. if let duration = info[durationUserInfoKey] as? TimeInterval {
  1229. if duration != 0 {
  1230. // Setitng keyboard animation duration
  1231. _animationDuration = duration
  1232. }
  1233. }
  1234. }
  1235. //If not enabled then do nothing.
  1236. if privateIsEnabled() == false {
  1237. return
  1238. }
  1239. let startTime = CACurrentMediaTime()
  1240. showLog("****** \(#function) started ******", indentation: 1)
  1241. //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
  1242. // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
  1243. // if (_textFieldView == nil) return
  1244. //Restoring the contentOffset of the lastScrollView
  1245. if let lastScrollView = _lastScrollView {
  1246. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1247. if lastScrollView.contentInset != self._startingContentInsets {
  1248. self.showLog("Restoring contentInset to: \(self._startingContentInsets)")
  1249. lastScrollView.contentInset = self._startingContentInsets
  1250. lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
  1251. }
  1252. if lastScrollView.shouldRestoreScrollViewContentOffset == true && lastScrollView.contentOffset.equalTo(self._startingContentOffset) == false {
  1253. self.showLog("Restoring contentOffset to: \(self._startingContentOffset)")
  1254. var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
  1255. if #available(iOS 9, *) {
  1256. animatedContentOffset = self._textFieldView?.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil
  1257. }
  1258. if animatedContentOffset {
  1259. lastScrollView.setContentOffset(self._startingContentOffset, animated: UIView.areAnimationsEnabled)
  1260. } else {
  1261. lastScrollView.contentOffset = self._startingContentOffset
  1262. }
  1263. }
  1264. // TODO: restore scrollView state
  1265. // This is temporary solution. Have to implement the save and restore scrollView state
  1266. var superScrollView: UIScrollView? = lastScrollView
  1267. while let scrollView = superScrollView {
  1268. let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
  1269. let minimumY = contentSize.height - scrollView.frame.height
  1270. if minimumY < scrollView.contentOffset.y {
  1271. let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
  1272. if scrollView.contentOffset.equalTo(newContentOffset) == false {
  1273. var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
  1274. if #available(iOS 9, *) {
  1275. animatedContentOffset = self._textFieldView?.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil
  1276. }
  1277. if animatedContentOffset {
  1278. scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
  1279. } else {
  1280. scrollView.contentOffset = newContentOffset
  1281. }
  1282. self.showLog("Restoring contentOffset to: \(self._startingContentOffset)")
  1283. }
  1284. }
  1285. superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
  1286. }
  1287. })
  1288. }
  1289. restorePosition()
  1290. //Reset all values
  1291. _lastScrollView = nil
  1292. _kbFrame = CGRect.zero
  1293. _startingContentInsets = UIEdgeInsets()
  1294. _startingScrollIndicatorInsets = UIEdgeInsets()
  1295. _startingContentOffset = CGPoint.zero
  1296. // topViewBeginRect = CGRectZero //Commented due to #82
  1297. let elapsedTime = CACurrentMediaTime() - startTime
  1298. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1299. }
  1300. @objc internal func keyboardDidHide(_ notification: Notification) {
  1301. let startTime = CACurrentMediaTime()
  1302. showLog("****** \(#function) started ******", indentation: 1)
  1303. _topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
  1304. _kbFrame = CGRect.zero
  1305. let elapsedTime = CACurrentMediaTime() - startTime
  1306. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1307. }
  1308. ///-------------------------------------------
  1309. // MARK: UITextField/UITextView Notifications
  1310. ///-------------------------------------------
  1311. /** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
  1312. @objc internal func textFieldViewDidBeginEditing(_ notification: Notification) {
  1313. let startTime = CACurrentMediaTime()
  1314. showLog("****** \(#function) started ******", indentation: 1)
  1315. // Getting object
  1316. _textFieldView = notification.object as? UIView
  1317. if overrideKeyboardAppearance == true {
  1318. if let textFieldView = _textFieldView as? UITextField {
  1319. //If keyboard appearance is not like the provided appearance
  1320. if textFieldView.keyboardAppearance != keyboardAppearance {
  1321. //Setting textField keyboard appearance and reloading inputViews.
  1322. textFieldView.keyboardAppearance = keyboardAppearance
  1323. textFieldView.reloadInputViews()
  1324. }
  1325. } else if let textFieldView = _textFieldView as? UITextView {
  1326. //If keyboard appearance is not like the provided appearance
  1327. if textFieldView.keyboardAppearance != keyboardAppearance {
  1328. //Setting textField keyboard appearance and reloading inputViews.
  1329. textFieldView.keyboardAppearance = keyboardAppearance
  1330. textFieldView.reloadInputViews()
  1331. }
  1332. }
  1333. }
  1334. //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
  1335. if privateIsEnableAutoToolbar() == true {
  1336. //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
  1337. if let textView = _textFieldView as? UITextView,
  1338. textView.inputAccessoryView == nil {
  1339. UIView.animate(withDuration: 0.00001, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1340. self.addToolbarIfRequired()
  1341. }, completion: { (_) -> Void in
  1342. //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
  1343. textView.reloadInputViews()
  1344. })
  1345. } else {
  1346. //Adding toolbar
  1347. addToolbarIfRequired()
  1348. }
  1349. } else {
  1350. removeToolbarIfRequired()
  1351. }
  1352. resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
  1353. _textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture) // (Enhancement ID: #14)
  1354. if privateIsEnabled() == true {
  1355. if _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == true { // (Bug ID: #5)
  1356. _rootViewController = _textFieldView?.parentContainerViewController()
  1357. if let controller = _rootViewController {
  1358. if _rootViewControllerWhilePopGestureRecognizerActive == controller {
  1359. _topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive
  1360. } else {
  1361. _topViewBeginOrigin = controller.view.frame.origin
  1362. }
  1363. _rootViewControllerWhilePopGestureRecognizerActive = nil
  1364. _topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
  1365. self.showLog("Saving \(controller) beginning origin: \(self._topViewBeginOrigin)")
  1366. }
  1367. }
  1368. //If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
  1369. //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
  1370. if _privateIsKeyboardShowing == true,
  1371. let textFieldView = _textFieldView,
  1372. textFieldView.isAlertViewTextField() == false {
  1373. // keyboard is already showing. adjust position.
  1374. optimizedAdjustPosition()
  1375. }
  1376. }
  1377. let elapsedTime = CACurrentMediaTime() - startTime
  1378. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1379. }
  1380. /** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
  1381. @objc internal func textFieldViewDidEndEditing(_ notification: Notification) {
  1382. let startTime = CACurrentMediaTime()
  1383. showLog("****** \(#function) started ******", indentation: 1)
  1384. //Removing gesture recognizer (Enhancement ID: #14)
  1385. _textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture)
  1386. // We check if there's a change in original frame or not.
  1387. if let textView = _textFieldView as? UITextView {
  1388. if isTextViewContentInsetChanged == true {
  1389. self.isTextViewContentInsetChanged = false
  1390. if textView.contentInset != self.startingTextViewContentInsets {
  1391. self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
  1392. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1393. //Setting textField to it's initial contentInset
  1394. textView.contentInset = self.startingTextViewContentInsets
  1395. textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
  1396. }, completion: { (_) -> Void in })
  1397. }
  1398. }
  1399. }
  1400. //Setting object to nil
  1401. _textFieldView = nil
  1402. let elapsedTime = CACurrentMediaTime() - startTime
  1403. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1404. }
  1405. ///---------------------------------------
  1406. // MARK: UIStatusBar Notification methods
  1407. ///---------------------------------------
  1408. /** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
  1409. @objc internal func willChangeStatusBarOrientation(_ notification: Notification) {
  1410. let currentStatusBarOrientation: UIInterfaceOrientation
  1411. #if swift(>=5.1)
  1412. if #available(iOS 13, *) {
  1413. currentStatusBarOrientation = keyWindow()?.windowScene?.interfaceOrientation ?? UIInterfaceOrientation.unknown
  1414. } else {
  1415. currentStatusBarOrientation = UIApplication.shared.statusBarOrientation
  1416. }
  1417. #else
  1418. currentStatusBarOrientation = UIApplication.shared.statusBarOrientation
  1419. #endif
  1420. guard let statusBarOrientation = notification.userInfo?[UIApplication.statusBarOrientationUserInfoKey] as? Int, currentStatusBarOrientation.rawValue != statusBarOrientation else {
  1421. return
  1422. }
  1423. let startTime = CACurrentMediaTime()
  1424. showLog("****** \(#function) started ******", indentation: 1)
  1425. //If textViewContentInsetChanged is saved then restore it.
  1426. if let textView = _textFieldView as? UITextView {
  1427. if isTextViewContentInsetChanged == true {
  1428. self.isTextViewContentInsetChanged = false
  1429. if textView.contentInset != self.startingTextViewContentInsets {
  1430. UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
  1431. self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
  1432. //Setting textField to it's initial contentInset
  1433. textView.contentInset = self.startingTextViewContentInsets
  1434. textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
  1435. }, completion: { (_) -> Void in })
  1436. }
  1437. }
  1438. }
  1439. restorePosition()
  1440. let elapsedTime = CACurrentMediaTime() - startTime
  1441. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1442. }
  1443. ///------------------
  1444. // MARK: AutoToolbar
  1445. ///------------------
  1446. /** Get all UITextField/UITextView siblings of textFieldView. */
  1447. private func responderViews() -> [UIView]? {
  1448. var superConsideredView: UIView?
  1449. //If find any consider responderView in it's upper hierarchy then will get deepResponderView.
  1450. for disabledClass in toolbarPreviousNextAllowedClasses {
  1451. superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
  1452. if superConsideredView != nil {
  1453. break
  1454. }
  1455. }
  1456. //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)
  1457. if let view = superConsideredView {
  1458. return view.deepResponderViews()
  1459. } else { //Otherwise fetching all the siblings
  1460. if let textFields = _textFieldView?.responderSiblings() {
  1461. //Sorting textFields according to behaviour
  1462. switch toolbarManageBehaviour {
  1463. //If autoToolbar behaviour is bySubviews, then returning it.
  1464. case IQAutoToolbarManageBehaviour.bySubviews: return textFields
  1465. //If autoToolbar behaviour is by tag, then sorting it according to tag property.
  1466. case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag()
  1467. //If autoToolbar behaviour is by tag, then sorting it according to tag property.
  1468. case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition()
  1469. }
  1470. } else {
  1471. return nil
  1472. }
  1473. }
  1474. }
  1475. /** Add toolbar if it is required to add on textFields and it's siblings. */
  1476. private func addToolbarIfRequired() {
  1477. let startTime = CACurrentMediaTime()
  1478. showLog("****** \(#function) started ******", indentation: 1)
  1479. // Getting all the sibling textFields.
  1480. if let siblings = responderViews(), !siblings.isEmpty {
  1481. showLog("Found \(siblings.count) responder sibling(s)")
  1482. if let textField = _textFieldView {
  1483. //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
  1484. //setInputAccessoryView: check (Bug ID: #307)
  1485. if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
  1486. if textField.inputAccessoryView == nil ||
  1487. textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
  1488. textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
  1489. let rightConfiguration: IQBarButtonItemConfiguration
  1490. if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
  1491. rightConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.doneAction(_:)))
  1492. } else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
  1493. rightConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.doneAction(_:)))
  1494. } else {
  1495. rightConfiguration = IQBarButtonItemConfiguration(barButtonSystemItem: .done, action: #selector(self.doneAction(_:)))
  1496. }
  1497. // If only one object is found, then adding only Done button.
  1498. if (siblings.count == 1 && previousNextDisplayMode == .default) || previousNextDisplayMode == .alwaysHide {
  1499. textField.addKeyboardToolbarWithTarget(target: self, titleText: (shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder: nil), rightBarButtonConfiguration: rightConfiguration, previousBarButtonConfiguration: nil, nextBarButtonConfiguration: nil)
  1500. textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
  1501. } else if (siblings.count > 1 && previousNextDisplayMode == .default) || previousNextDisplayMode == .alwaysShow {
  1502. let prevConfiguration: IQBarButtonItemConfiguration
  1503. if let doneBarButtonItemImage = toolbarPreviousBarButtonItemImage {
  1504. prevConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.previousAction(_:)))
  1505. } else if let doneBarButtonItemText = toolbarPreviousBarButtonItemText {
  1506. prevConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.previousAction(_:)))
  1507. } else {
  1508. prevConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardPreviousImage() ?? UIImage()), action: #selector(self.previousAction(_:)))
  1509. }
  1510. let nextConfiguration: IQBarButtonItemConfiguration
  1511. if let doneBarButtonItemImage = toolbarNextBarButtonItemImage {
  1512. nextConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.nextAction(_:)))
  1513. } else if let doneBarButtonItemText = toolbarNextBarButtonItemText {
  1514. nextConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.nextAction(_:)))
  1515. } else {
  1516. nextConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardNextImage() ?? UIImage()), action: #selector(self.nextAction(_:)))
  1517. }
  1518. textField.addKeyboardToolbarWithTarget(target: self, titleText: (shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder: nil), rightBarButtonConfiguration: rightConfiguration, previousBarButtonConfiguration: prevConfiguration, nextBarButtonConfiguration: nextConfiguration)
  1519. textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
  1520. }
  1521. let toolbar = textField.keyboardToolbar
  1522. // Setting toolbar to keyboard.
  1523. if let textField = textField as? UITextField {
  1524. //Bar style according to keyboard appearance
  1525. switch textField.keyboardAppearance {
  1526. case .dark:
  1527. toolbar.barStyle = UIBarStyle.black
  1528. toolbar.tintColor = UIColor.white
  1529. toolbar.barTintColor = nil
  1530. default:
  1531. toolbar.barStyle = UIBarStyle.default
  1532. toolbar.barTintColor = toolbarBarTintColor
  1533. //Setting toolbar tintColor // (Enhancement ID: #30)
  1534. if shouldToolbarUsesTextFieldTintColor {
  1535. toolbar.tintColor = textField.tintColor
  1536. } else if let tintColor = toolbarTintColor {
  1537. toolbar.tintColor = tintColor
  1538. } else {
  1539. toolbar.tintColor = UIColor.black
  1540. }
  1541. }
  1542. } else if let textView = textField as? UITextView {
  1543. //Bar style according to keyboard appearance
  1544. switch textView.keyboardAppearance {
  1545. case .dark:
  1546. toolbar.barStyle = UIBarStyle.black
  1547. toolbar.tintColor = UIColor.white
  1548. toolbar.barTintColor = nil
  1549. default:
  1550. toolbar.barStyle = UIBarStyle.default
  1551. toolbar.barTintColor = toolbarBarTintColor
  1552. if shouldToolbarUsesTextFieldTintColor {
  1553. toolbar.tintColor = textView.tintColor
  1554. } else if let tintColor = toolbarTintColor {
  1555. toolbar.tintColor = tintColor
  1556. } else {
  1557. toolbar.tintColor = UIColor.black
  1558. }
  1559. }
  1560. }
  1561. //Setting toolbar title font. // (Enhancement ID: #30)
  1562. if shouldShowToolbarPlaceholder == true &&
  1563. textField.shouldHideToolbarPlaceholder == false {
  1564. //Updating placeholder font to toolbar. //(Bug ID: #148, #272)
  1565. if toolbar.titleBarButton.title == nil ||
  1566. toolbar.titleBarButton.title != textField.drawingToolbarPlaceholder {
  1567. toolbar.titleBarButton.title = textField.drawingToolbarPlaceholder
  1568. }
  1569. //Setting toolbar title font. // (Enhancement ID: #30)
  1570. if let font = placeholderFont {
  1571. toolbar.titleBarButton.titleFont = font
  1572. }
  1573. //Setting toolbar title color. // (Enhancement ID: #880)
  1574. if let color = placeholderColor {
  1575. toolbar.titleBarButton.titleColor = color
  1576. }
  1577. //Setting toolbar button title color. // (Enhancement ID: #880)
  1578. if let color = placeholderButtonColor {
  1579. toolbar.titleBarButton.selectableTitleColor = color
  1580. }
  1581. } else {
  1582. toolbar.titleBarButton.title = nil
  1583. }
  1584. //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
  1585. // If firstTextField, then previous should not be enabled.
  1586. if siblings.first == textField {
  1587. if siblings.count == 1 {
  1588. textField.keyboardToolbar.previousBarButton.isEnabled = false
  1589. textField.keyboardToolbar.nextBarButton.isEnabled = false
  1590. } else {
  1591. textField.keyboardToolbar.previousBarButton.isEnabled = false
  1592. textField.keyboardToolbar.nextBarButton.isEnabled = true
  1593. }
  1594. } else if siblings.last == textField { // If lastTextField then next should not be enaled.
  1595. textField.keyboardToolbar.previousBarButton.isEnabled = true
  1596. textField.keyboardToolbar.nextBarButton.isEnabled = false
  1597. } else {
  1598. textField.keyboardToolbar.previousBarButton.isEnabled = true
  1599. textField.keyboardToolbar.nextBarButton.isEnabled = true
  1600. }
  1601. }
  1602. }
  1603. }
  1604. }
  1605. let elapsedTime = CACurrentMediaTime() - startTime
  1606. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1607. }
  1608. /** Remove any toolbar if it is IQToolbar. */
  1609. private func removeToolbarIfRequired() { // (Bug ID: #18)
  1610. let startTime = CACurrentMediaTime()
  1611. showLog("****** \(#function) started ******", indentation: 1)
  1612. // Getting all the sibling textFields.
  1613. if let siblings = responderViews() {
  1614. showLog("Found \(siblings.count) responder sibling(s)")
  1615. for view in siblings {
  1616. if let toolbar = view.inputAccessoryView as? IQToolbar {
  1617. //setInputAccessoryView: check (Bug ID: #307)
  1618. if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
  1619. (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
  1620. if let textField = view as? UITextField {
  1621. textField.inputAccessoryView = nil
  1622. textField.reloadInputViews()
  1623. } else if let textView = view as? UITextView {
  1624. textView.inputAccessoryView = nil
  1625. textView.reloadInputViews()
  1626. }
  1627. }
  1628. }
  1629. }
  1630. }
  1631. let elapsedTime = CACurrentMediaTime() - startTime
  1632. showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
  1633. }
  1634. /** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
  1635. @objc public func reloadInputViews() {
  1636. //If enabled then adding toolbar.
  1637. if privateIsEnableAutoToolbar() == true {
  1638. self.addToolbarIfRequired()
  1639. } else {
  1640. self.removeToolbarIfRequired()
  1641. }
  1642. }
  1643. ///------------------------------------
  1644. // MARK: Debugging & Developer options
  1645. ///------------------------------------
  1646. @objc public var enableDebugging = false
  1647. /**
  1648. @warning Use below methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk.
  1649. */
  1650. @objc public func registerAllNotifications() {
  1651. #if swift(>=4.2)
  1652. let UIKeyboardWillShow = UIResponder.keyboardWillShowNotification
  1653. let UIKeyboardDidShow = UIResponder.keyboardDidShowNotification
  1654. let UIKeyboardWillHide = UIResponder.keyboardWillHideNotification
  1655. let UIKeyboardDidHide = UIResponder.keyboardDidHideNotification
  1656. let UITextFieldTextDidBeginEditing = UITextField.textDidBeginEditingNotification
  1657. let UITextFieldTextDidEndEditing = UITextField.textDidEndEditingNotification
  1658. let UITextViewTextDidBeginEditing = UITextView.textDidBeginEditingNotification
  1659. let UITextViewTextDidEndEditing = UITextView.textDidEndEditingNotification
  1660. let UIApplicationWillChangeStatusBarOrientation = UIApplication.willChangeStatusBarOrientationNotification
  1661. #else
  1662. let UIKeyboardWillShow = Notification.Name.UIKeyboardWillShow
  1663. let UIKeyboardDidShow = Notification.Name.UIKeyboardDidShow
  1664. let UIKeyboardWillHide = Notification.Name.UIKeyboardWillHide
  1665. let UIKeyboardDidHide = Notification.Name.UIKeyboardDidHide
  1666. let UITextFieldTextDidBeginEditing = Notification.Name.UITextFieldTextDidBeginEditing
  1667. let UITextFieldTextDidEndEditing = Notification.Name.UITextFieldTextDidEndEditing
  1668. let UITextViewTextDidBeginEditing = Notification.Name.UITextViewTextDidBeginEditing
  1669. let UITextViewTextDidEndEditing = Notification.Name.UITextViewTextDidEndEditing
  1670. let UIApplicationWillChangeStatusBarOrientation = Notification.Name.UIApplicationWillChangeStatusBarOrientation
  1671. #endif
  1672. // Registering for keyboard notification.
  1673. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIKeyboardWillShow, object: nil)
  1674. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: UIKeyboardDidShow, object: nil)
  1675. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIKeyboardWillHide, object: nil)
  1676. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: UIKeyboardDidHide, object: nil)
  1677. // Registering for UITextField notification.
  1678. registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextFieldTextDidEndEditing.rawValue)
  1679. // Registering for UITextView notification.
  1680. registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextViewTextDidEndEditing.rawValue)
  1681. // Registering for orientation changes notification
  1682. NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
  1683. }
  1684. @objc public func unregisterAllNotifications() {
  1685. #if swift(>=4.2)
  1686. let UIKeyboardWillShow = UIResponder.keyboardWillShowNotification
  1687. let UIKeyboardDidShow = UIResponder.keyboardDidShowNotification
  1688. let UIKeyboardWillHide = UIResponder.keyboardWillHideNotification
  1689. let UIKeyboardDidHide = UIResponder.keyboardDidHideNotification
  1690. let UITextFieldTextDidBeginEditing = UITextField.textDidBeginEditingNotification
  1691. let UITextFieldTextDidEndEditing = UITextField.textDidEndEditingNotification
  1692. let UITextViewTextDidBeginEditing = UITextView.textDidBeginEditingNotification
  1693. let UITextViewTextDidEndEditing = UITextView.textDidEndEditingNotification
  1694. let UIApplicationWillChangeStatusBarOrientation = UIApplication.willChangeStatusBarOrientationNotification
  1695. #else
  1696. let UIKeyboardWillShow = Notification.Name.UIKeyboardWillShow
  1697. let UIKeyboardDidShow = Notification.Name.UIKeyboardDidShow
  1698. let UIKeyboardWillHide = Notification.Name.UIKeyboardWillHide
  1699. let UIKeyboardDidHide = Notification.Name.UIKeyboardDidHide
  1700. let UITextFieldTextDidBeginEditing = Notification.Name.UITextFieldTextDidBeginEditing
  1701. let UITextFieldTextDidEndEditing = Notification.Name.UITextFieldTextDidEndEditing
  1702. let UITextViewTextDidBeginEditing = Notification.Name.UITextViewTextDidBeginEditing
  1703. let UITextViewTextDidEndEditing = Notification.Name.UITextViewTextDidEndEditing
  1704. let UIApplicationWillChangeStatusBarOrientation = Notification.Name.UIApplicationWillChangeStatusBarOrientation
  1705. #endif
  1706. // Unregistering for keyboard notification.
  1707. NotificationCenter.default.removeObserver(self, name: UIKeyboardWillShow, object: nil)
  1708. NotificationCenter.default.removeObserver(self, name: UIKeyboardDidShow, object: nil)
  1709. NotificationCenter.default.removeObserver(self, name: UIKeyboardWillHide, object: nil)
  1710. NotificationCenter.default.removeObserver(self, name: UIKeyboardDidHide, object: nil)
  1711. // Unregistering for UITextField notification.
  1712. unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextFieldTextDidEndEditing.rawValue)
  1713. // Unregistering for UITextView notification.
  1714. unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextViewTextDidEndEditing.rawValue)
  1715. // Unregistering for orientation changes notification
  1716. NotificationCenter.default.removeObserver(self, name: UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
  1717. }
  1718. private func showLog(_ logString: String, indentation: Int = 0) {
  1719. struct Static {
  1720. static var indentation = 0
  1721. }
  1722. if indentation < 0 {
  1723. Static.indentation = max(0, Static.indentation + indentation)
  1724. }
  1725. if enableDebugging {
  1726. var preLog = "IQKeyboardManager"
  1727. for _ in 0 ... Static.indentation {
  1728. preLog += "|\t"
  1729. }
  1730. print(preLog + logString)
  1731. }
  1732. if indentation > 0 {
  1733. Static.indentation += indentation
  1734. }
  1735. }
  1736. }