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