fix
杨锴
2025-06-16 3fa53409f5132333ce6d83fff796e108ddd62090
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
//
//  IQKeyboardManager+UITextFieldViewNotification.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 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 Foundation - UIKit contains Foundation
import UIKit
 
// MARK: UITextField/UITextView Notifications
@available(iOSApplicationExtension, unavailable)
internal extension IQKeyboardManager {
 
    private struct AssociatedKeys {
        static var textFieldView: Int = 0
        static var topViewBeginOrigin: Int = 0
        static var topViewBeginSafeAreaInsets: Int = 0
        static var rootViewController: Int = 0
        static var rootViewControllerWhilePopGestureRecognizerActive: Int = 0
        static var topViewBeginOriginWhilePopGestureRecognizerActive: Int = 0
    }
 
    /** To save UITextField/UITextView object voa textField/textView notifications. */
    weak var textFieldView: UIView? {
        get {
            return (objc_getAssociatedObject(self, &AssociatedKeys.textFieldView) as? WeakObjectContainer)?.object as? UIView
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.textFieldView, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
 
    var topViewBeginOrigin: CGPoint {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginOrigin) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginOrigin, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
 
    var topViewBeginSafeAreaInsets: UIEdgeInsets {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginSafeAreaInsets) as? UIEdgeInsets ?? .zero
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginSafeAreaInsets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
 
    /** To save rootViewController */
    weak var rootViewController: UIViewController? {
        get {
            return (objc_getAssociatedObject(self, &AssociatedKeys.rootViewController) as? WeakObjectContainer)?.object as? UIViewController
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.rootViewController, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
 
    /** To overcome with popGestureRecognizer issue Bug ID: #1361 */
    weak var rootViewControllerWhilePopGestureRecognizerActive: UIViewController? {
        get {
            return (objc_getAssociatedObject(self, &AssociatedKeys.rootViewControllerWhilePopGestureRecognizerActive) as? WeakObjectContainer)?.object as? UIViewController
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.rootViewControllerWhilePopGestureRecognizerActive, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
 
    var topViewBeginOriginWhilePopGestureRecognizerActive: CGPoint {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginOriginWhilePopGestureRecognizerActive) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginOriginWhilePopGestureRecognizerActive, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
 
    /**  UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
    @objc func textFieldViewDidBeginEditing(_ notification: Notification) {
 
        guard let object = notification.object as? UIView, let isKeyWindow = object.window?.isKeyWindow, isKeyWindow else {
            return
        }
 
        let startTime = CACurrentMediaTime()
        showLog("📝>>>>> \(#function) started >>>>>", indentation: 1)
        showLog("Notification Object:\(notification.object ?? "NULL")")
 
        //  Getting object
        textFieldView = notification.object as? UIView
 
        if overrideKeyboardAppearance, let textInput = textFieldView as? UITextInput, textInput.keyboardAppearance != keyboardAppearance {
            // Setting textField keyboard appearance and reloading inputViews.
            if let textFieldView = textFieldView as? UITextField {
                textFieldView.keyboardAppearance = keyboardAppearance
            } else if  let textFieldView = textFieldView as? UITextView {
                textFieldView.keyboardAppearance = keyboardAppearance
            }
            textFieldView?.reloadInputViews()
        }
 
        // If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
        if privateIsEnableAutoToolbar() {
 
            // 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.
            if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)),
                textView.inputAccessoryView == nil {
                self.addToolbarIfRequired()
            } else {
                // Adding toolbar
                addToolbarIfRequired()
            }
        } else {
            removeToolbarIfRequired()
        }
 
        resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
        textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture)    //   (Enhancement ID: #14)
 
        if privateIsEnabled() == false {
            restorePosition()
            topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
            topViewBeginSafeAreaInsets = .zero
        } else {
            if topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) {    //  (Bug ID: #5)
 
                rootViewController = textFieldView?.parentContainerViewController()
 
                if let controller = rootViewController {
 
                    if rootViewControllerWhilePopGestureRecognizerActive == controller {
                        topViewBeginOrigin = topViewBeginOriginWhilePopGestureRecognizerActive
                    } else {
                        topViewBeginOrigin = controller.view.frame.origin
                        topViewBeginSafeAreaInsets = controller.view.safeAreaInsets
                    }
 
                    rootViewControllerWhilePopGestureRecognizerActive = nil
                    topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
 
                    self.showLog("Saving \(controller) beginning origin: \(self.topViewBeginOrigin)")
                }
            }
 
            // If textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
            // 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).
            if keyboardShowing,
                let textFieldView = textFieldView,
                textFieldView.isAlertViewTextField() == false {
 
                //  keyboard is already showing. adjust position.
                self.adjustPosition()
            }
        }
 
        let elapsedTime = CACurrentMediaTime() - startTime
        showLog("📝<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
    }
 
    /**  UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
    @objc func textFieldViewDidEndEditing(_ notification: Notification) {
 
        guard let object = notification.object as? UIView, let isKeyWindow = object.window?.isKeyWindow, isKeyWindow else {
            return
        }
 
        let startTime = CACurrentMediaTime()
        showLog("📝>>>>> \(#function) started >>>>>", indentation: 1)
        showLog("Notification Object:\(notification.object ?? "NULL")")
 
        // Removing gesture recognizer   (Enhancement ID: #14)
        textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture)
 
        // We check if there's a change in original frame or not.
 
        if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)) {
 
            if isTextViewContentInsetChanged {
                self.isTextViewContentInsetChanged = false
 
                if textView.contentInset != self.startingTextViewContentInsets {
                    self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
 
                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
 
                        // Setting textField to it's initial contentInset
                        textView.contentInset = self.startingTextViewContentInsets
                        textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
 
                    }, completion: { (_) -> Void in })
                }
            }
        }
 
        // Setting object to nil
#if swift(>=5.7)
        if #available(iOS 16.0, *), let textView = object as? UITextView, textView.isFindInteractionEnabled {
                // Not setting it nil, because it may be doing find interaction.
                // As of now, here textView.findInteraction?.isFindNavigatorVisible returns false
                // So there is no way to detect if this is dismissed due to findInteraction
        } else {
            textFieldView = nil
        }
 #else
        textFieldView = nil
#endif
 
        let elapsedTime = CACurrentMediaTime() - startTime
        showLog("📝<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
    }
}