2 // IQKeyboardManager.swift
3 // https://github.com/hackiftekhar/IQKeyboardManager
4 // Copyright (c) 2013-24 Iftekhar Qurashi.
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:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
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
28 // MARK: IQToolbar tags
30 // swiftlint:disable line_length
31 // A generic version of KeyboardManagement. (OLD DOCUMENTATION) LINK
32 // https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
33 // https://developer.apple.com/documentation/uikit/keyboards_and_input/adjusting_your_layout_with_keyboard_layout_guide
34 // swiftlint:enable line_length
37 Code-less drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView.
38 Neither need to write any code nor any setup required and much more.
40 @available(iOSApplicationExtension, unavailable)
42 @objc public final class IQKeyboardManager: NSObject {
45 Returns the default singleton instance.
47 @objc public static let shared: IQKeyboardManager = .init()
49 // MARK: UIKeyboard handling
52 Enable/disable managing distance between keyboard and textField.
53 Default is YES(Enabled when class loads in `+(void)load` method).
55 @objc public var enable: Bool = false {
58 // If not enable, enable it.
59 if enable, !oldValue {
60 // If keyboard is currently showing.
61 if activeConfiguration.keyboardInfo.keyboardShowing {
67 } else if !enable, oldValue { // If not disable, disable it.
75 To set keyboard distance from textField. can't be less than zero. Default is 10.0.
77 @objc public var keyboardDistanceFromTextField: CGFloat = 10.0
79 // MARK: IQToolbar handling
82 Automatic add the IQToolbar functionality. Default is YES.
84 @objc public var enableAutoToolbar: Bool = true {
87 showLog("enableAutoToolbar: \(enableAutoToolbar ? "Yes" : "NO")")
91 internal var activeConfiguration: IQActiveConfiguration = .init()
94 Configurations related to the toolbar display over the keyboard.
96 @objc public let toolbarConfiguration: IQToolbarConfiguration = .init()
99 Configuration related to keyboard appearance
101 @objc public let keyboardConfiguration: IQKeyboardConfiguration = .init()
103 // MARK: UITextField/UITextView Next/Previous/Resign handling
106 Resigns Keyboard on touching outside of UITextField/View. Default is NO.
108 @objc public var resignOnTouchOutside: Bool = false {
111 resignFirstResponderGesture.isEnabled = privateResignOnTouchOutside()
113 showLog("resignOnTouchOutside: \(resignOnTouchOutside ? "Yes" : "NO")")
117 /** TapGesture to resign keyboard on view's touch.
118 It's a readonly property and exposed only for adding/removing dependencies
119 if your added gesture does have collision with this one
121 @objc public lazy var resignFirstResponderGesture: UITapGestureRecognizer = {
123 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
124 tapGesture.cancelsTouchesInView = false
125 tapGesture.delegate = self
130 /*******************************************/
133 Resigns currently first responder field.
136 @objc public func resignFirstResponder() -> Bool {
138 guard let textFieldRetain: UIView = activeConfiguration.textFieldViewInfo?.textFieldView else {
142 // Resigning first responder
143 guard textFieldRetain.resignFirstResponder() else {
144 showLog("Refuses to resign first responder: \(textFieldRetain)")
145 // If it refuses then becoming it as first responder again. (Bug ID: #96)
146 // If it refuses to resign then becoming it first responder again for getting notifications callback.
147 textFieldRetain.becomeFirstResponder()
153 // MARK: UISound handling
156 If YES, then it plays inputClick sound on next/previous/done click.
158 @objc public var playInputClicks: Bool = true
160 // MARK: UIAnimation handling
163 If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
165 @objc public var layoutIfNeededOnUpdate: Bool = false
167 // MARK: Class Level disabling methods
170 Disable distance handling within the scope of disabled distance handling viewControllers classes.
171 Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
173 @objc public var disabledDistanceHandlingClasses: [UIViewController.Type] = []
176 Enable distance handling within the scope of enabled distance handling viewControllers classes.
177 Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
178 If same Class is added in disabledDistanceHandlingClasses list,
179 then enabledDistanceHandlingClasses will be ignored.
181 @objc public var enabledDistanceHandlingClasses: [UIViewController.Type] = []
184 Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes.
185 Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
187 @objc public var disabledToolbarClasses: [UIViewController.Type] = []
190 Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes.
191 Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
192 If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
194 @objc public var enabledToolbarClasses: [UIViewController.Type] = []
197 Allowed subclasses of UIView to add all inner textField,
198 this will allow to navigate between textField contains in different superview.
199 Class should be kind of UIView.
201 @objc public var toolbarPreviousNextAllowedClasses: [UIView.Type] = []
204 Disabled classes to ignore resignOnTouchOutside' property, Class should be kind of UIViewController.
206 @objc public var disabledTouchResignedClasses: [UIViewController.Type] = []
209 Enabled classes to forcefully enable 'resignOnTouchOutside' property.
210 Class should be kind of UIViewController
211 . If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
213 @objc public var enabledTouchResignedClasses: [UIViewController.Type] = []
216 if resignOnTouchOutside is enabled then you can customize the behavior
217 to not recognize gesture touches on some specific view subclasses.
218 Class should be kind of UIView. Default is [UIControl, UINavigationBar]
220 @objc public var touchResignedGestureIgnoreClasses: [UIView.Type] = []
222 // MARK: Third Party Library support
223 /// Add TextField/TextView Notifications customized Notifications.
224 /// For example while using YYTextView https://github.com/ibireme/YYText
226 /**************************************************************************************/
228 // MARK: Initialization/De-initialization
230 /* Singleton Object Initialization. */
235 self.addActiveConfigurationObserver()
237 // Creating gesture for resignOnTouchOutside. (Enhancement ID: #14)
238 resignFirstResponderGesture.isEnabled = resignOnTouchOutside
240 disabledDistanceHandlingClasses.append(UITableViewController.self)
241 disabledDistanceHandlingClasses.append(UIInputViewController.self)
242 disabledDistanceHandlingClasses.append(UIAlertController.self)
244 disabledToolbarClasses.append(UIAlertController.self)
245 disabledToolbarClasses.append(UIInputViewController.self)
247 disabledTouchResignedClasses.append(UIAlertController.self)
248 disabledTouchResignedClasses.append(UIInputViewController.self)
250 toolbarPreviousNextAllowedClasses.append(UITableView.self)
251 toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
252 toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
254 touchResignedGestureIgnoreClasses.append(UIControl.self)
255 touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
257 NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)),
258 name: UIApplication.didBecomeActiveNotification, object: nil)
261 // Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay
262 // If you experience exception breakpoint issue at below line then try these solutions
263 // https://stackoverflow.com/questions/27375640/all-exception-break-point-is-stopping-for-no-reason-on-simulator
264 DispatchQueue.main.async {
265 let textField: UIView = UITextField()
266 textField.iq.addDone(target: nil, action: #selector(self.doneAction(_:)))
267 textField.iq.addPreviousNextDone(target: nil, previousAction: #selector(self.previousAction(_:)),
268 nextAction: #selector(self.nextAction(_:)),
269 doneAction: #selector(self.doneAction(_:)))
274 // Disable the keyboard manager.
278 // MARK: Public Methods
280 /* Refreshes textField/textView position if any external changes is explicitly made by user. */
281 @objc public func reloadLayoutIfNeeded() {
283 guard privateIsEnabled(),
284 activeConfiguration.keyboardInfo.keyboardShowing,
285 activeConfiguration.isReady else {
292 @available(iOSApplicationExtension, unavailable)
293 extension IQKeyboardManager: UIGestureRecognizerDelegate {
295 /** Resigning on tap gesture. (Enhancement ID: #14)*/
296 @objc private func tapRecognized(_ gesture: UITapGestureRecognizer) {
298 if gesture.state == .ended {
300 // Resigning currently responder textField.
301 resignFirstResponder()
305 /** Note: returning YES is guaranteed to allow simultaneous recognition.
306 returning NO is not guaranteed to prevent simultaneous recognition,
307 as the other gesture's delegate may return YES.
309 @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
310 shouldRecognizeSimultaneouslyWith
311 otherGestureRecognizer: UIGestureRecognizer) -> Bool {
316 To not detect touch events in a subclass of UIControl,
317 these may have added their own selector for specific work
319 @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
320 shouldReceive touch: UITouch) -> Bool {
322 // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...)
324 for ignoreClass in touchResignedGestureIgnoreClasses where touch.view?.isKind(of: ignoreClass) ?? false {