eeaca4b3eb59080373c3a9f761f6c6f80d7888cb
[mirrors/VoiceChatSdk_iOS.git] /
1 //
2 //  IQKeyboardManager.swift
3 //  https://github.com/hackiftekhar/IQKeyboardManager
4 //  Copyright (c) 2013-24 Iftekhar Qurashi.
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 // THE SOFTWARE.
23
24 import UIKit
25 import CoreGraphics
26 import QuartzCore
27
28 // MARK: IQToolbar tags
29
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
35
36 /**
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.
39 */
40 @available(iOSApplicationExtension, unavailable)
41 @MainActor
42 @objc public final class IQKeyboardManager: NSObject {
43
44     /**
45     Returns the default singleton instance.
46     */
47     @objc public static let shared: IQKeyboardManager = .init()
48
49     // MARK: UIKeyboard handling
50
51     /**
52     Enable/disable managing distance between keyboard and textField.
53      Default is YES(Enabled when class loads in `+(void)load` method).
54     */
55     @objc public var enable: Bool = false {
56
57         didSet {
58             // If not enable, enable it.
59             if enable, !oldValue {
60                 // If keyboard is currently showing.
61                 if activeConfiguration.keyboardInfo.keyboardShowing {
62                     adjustPosition()
63                 } else {
64                     restorePosition()
65                 }
66                 showLog("Enabled")
67             } else if !enable, oldValue {   // If not disable, disable it.
68                 restorePosition()
69                 showLog("Disabled")
70             }
71         }
72     }
73
74     /**
75     To set keyboard distance from textField. can't be less than zero. Default is 10.0.
76     */
77     @objc public var keyboardDistanceFromTextField: CGFloat = 10.0
78
79     // MARK: IQToolbar handling
80
81     /**
82     Automatic add the IQToolbar functionality. Default is YES.
83     */
84     @objc public var enableAutoToolbar: Bool = true {
85         didSet {
86             reloadInputViews()
87             showLog("enableAutoToolbar: \(enableAutoToolbar ? "Yes" : "NO")")
88         }
89     }
90
91     internal var activeConfiguration: IQActiveConfiguration = .init()
92
93     /**
94     Configurations related to the toolbar display over the keyboard.
95     */
96     @objc public let toolbarConfiguration: IQToolbarConfiguration = .init()
97
98     /**
99     Configuration related to keyboard appearance
100     */
101     @objc public let keyboardConfiguration: IQKeyboardConfiguration = .init()
102
103     // MARK: UITextField/UITextView Next/Previous/Resign handling
104
105     /**
106     Resigns Keyboard on touching outside of UITextField/View. Default is NO.
107     */
108     @objc public var resignOnTouchOutside: Bool = false {
109
110         didSet {
111             resignFirstResponderGesture.isEnabled = privateResignOnTouchOutside()
112
113             showLog("resignOnTouchOutside: \(resignOnTouchOutside ? "Yes" : "NO")")
114         }
115     }
116
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
120      */
121     @objc public lazy var resignFirstResponderGesture: UITapGestureRecognizer = {
122
123         let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
124         tapGesture.cancelsTouchesInView = false
125         tapGesture.delegate = self
126
127         return tapGesture
128     }()
129
130     /*******************************************/
131
132     /**
133     Resigns currently first responder field.
134     */
135     @discardableResult
136     @objc public func resignFirstResponder() -> Bool {
137
138         guard let textFieldRetain: UIView = activeConfiguration.textFieldViewInfo?.textFieldView else {
139             return false
140         }
141
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()
148             return false
149         }
150         return true
151     }
152
153     // MARK: UISound handling
154
155     /**
156     If YES, then it plays inputClick sound on next/previous/done click.
157     */
158     @objc public var playInputClicks: Bool = true
159
160     // MARK: UIAnimation handling
161
162     /**
163     If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
164     */
165     @objc public var layoutIfNeededOnUpdate: Bool = false
166
167     // MARK: Class Level disabling methods
168
169     /**
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.
172      */
173     @objc public var disabledDistanceHandlingClasses: [UIViewController.Type] = []
174
175     /**
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.
180      */
181     @objc public var enabledDistanceHandlingClasses: [UIViewController.Type] = []
182
183     /**
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.
186      */
187     @objc public var disabledToolbarClasses: [UIViewController.Type] = []
188
189     /**
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.
193      */
194     @objc public var enabledToolbarClasses: [UIViewController.Type] = []
195
196     /**
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.
200      */
201     @objc public var toolbarPreviousNextAllowedClasses: [UIView.Type] = []
202
203     /**
204      Disabled classes to ignore resignOnTouchOutside' property, Class should be kind of UIViewController.
205      */
206     @objc public var disabledTouchResignedClasses: [UIViewController.Type] = []
207
208     /**
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.
212      */
213     @objc public var enabledTouchResignedClasses: [UIViewController.Type] = []
214
215     /**
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]
219      */
220     @objc public var touchResignedGestureIgnoreClasses: [UIView.Type] = []
221
222     // MARK: Third Party Library support
223     /// Add TextField/TextView Notifications customized Notifications.
224     /// For example while using YYTextView https://github.com/ibireme/YYText
225
226    /**************************************************************************************/
227
228     // MARK: Initialization/De-initialization
229
230     /*  Singleton Object Initialization. */
231     override init() {
232
233         super.init()
234
235         self.addActiveConfigurationObserver()
236
237         // Creating gesture for resignOnTouchOutside. (Enhancement ID: #14)
238         resignFirstResponderGesture.isEnabled = resignOnTouchOutside
239
240         disabledDistanceHandlingClasses.append(UITableViewController.self)
241         disabledDistanceHandlingClasses.append(UIInputViewController.self)
242         disabledDistanceHandlingClasses.append(UIAlertController.self)
243
244         disabledToolbarClasses.append(UIAlertController.self)
245         disabledToolbarClasses.append(UIInputViewController.self)
246
247         disabledTouchResignedClasses.append(UIAlertController.self)
248         disabledTouchResignedClasses.append(UIInputViewController.self)
249
250         toolbarPreviousNextAllowedClasses.append(UITableView.self)
251         toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
252         toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
253
254         touchResignedGestureIgnoreClasses.append(UIControl.self)
255         touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
256
257         NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)),
258                                                name: UIApplication.didBecomeActiveNotification, object: nil)
259
260         // (Bug ID: #550)
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(_:)))
270         }
271     }
272
273     deinit {
274         //  Disable the keyboard manager.
275         enable = false
276     }
277
278     // MARK: Public Methods
279
280     /*  Refreshes textField/textView position if any external changes is explicitly made by user.   */
281     @objc public func reloadLayoutIfNeeded() {
282
283         guard privateIsEnabled(),
284               activeConfiguration.keyboardInfo.keyboardShowing,
285               activeConfiguration.isReady else {
286                 return
287         }
288         adjustPosition()
289     }
290 }
291
292 @available(iOSApplicationExtension, unavailable)
293 extension IQKeyboardManager: UIGestureRecognizerDelegate {
294
295     /** Resigning on tap gesture.   (Enhancement ID: #14)*/
296     @objc private func tapRecognized(_ gesture: UITapGestureRecognizer) {
297
298         if gesture.state == .ended {
299
300             // Resigning currently responder textField.
301             resignFirstResponder()
302         }
303     }
304
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.
308      */
309     @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
310                                         shouldRecognizeSimultaneouslyWith
311                                         otherGestureRecognizer: UIGestureRecognizer) -> Bool {
312         return false
313     }
314
315     /**
316      To not detect touch events in a subclass of UIControl,
317      these may have added their own selector for specific work
318      */
319     @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
320                                         shouldReceive touch: UITouch) -> Bool {
321         // (Bug ID: #145)
322         // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...)
323
324         for ignoreClass in touchResignedGestureIgnoreClasses where touch.view?.isKind(of: ignoreClass) ?? false {
325             return false
326         }
327
328         return true
329     }
330
331 }