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
//
//  IQKeyboardManager+Toolbar.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
 
@available(iOSApplicationExtension, unavailable)
public extension IQKeyboardManager {
 
    /**
    Default tag for toolbar with Done button   -1002.
    */
    private static let  kIQDoneButtonToolbarTag         =   -1002
 
    /**
    Default tag for toolbar with Previous/Next buttons -1005.
    */
    private static let  kIQPreviousNextButtonToolbarTag =   -1005
 
    // swiftlint:disable function_body_length
    // swiftlint:disable cyclomatic_complexity
    /**
     Add toolbar if it is required to add on textFields and it's siblings.
     */
    internal func addToolbarIfRequired() {
 
        // Either there is no inputAccessoryView or
        // if accessoryView is not appropriate for current situation
        // (There is Previous/Next/Done toolbar)
        guard let siblings: [UIView] = responderViews(), !siblings.isEmpty,
              let textField: UIView = activeConfiguration.textFieldViewInfo?.textFieldView,
              textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) else {
            return
        }
 
        if let inputAccessoryView: UIView = textField.inputAccessoryView {
 
            if inputAccessoryView.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
                inputAccessoryView.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
                // continue
            } else {
                let swiftUIAccessoryName: String = "InputAccessoryHost<InputAccessoryBar>"
                let classNameString: String = "\(type(of: inputAccessoryView.classForCoder))"
 
                // If it's SwiftUI accessory view but doesn't have a height (fake accessory view), then we should
                // add our own accessoryView otherwise, keep the SwiftUI accessoryView since user has added it from code
                guard classNameString.hasPrefix(swiftUIAccessoryName), inputAccessoryView.subviews.isEmpty else {
                    return
                }
            }
        }
 
        showLog(">>>>> \(#function) started >>>>>", indentation: 1)
        let startTime: CFTimeInterval = CACurrentMediaTime()
 
        showLog("Found \(siblings.count) responder sibling(s)")
 
        let rightConfiguration: IQBarButtonItemConfiguration
        if let configuration: IQBarButtonItemConfiguration = toolbarConfiguration.doneBarButtonConfiguration {
            rightConfiguration = configuration
            rightConfiguration.action = #selector(self.doneAction(_:))
        } else {
            rightConfiguration = IQBarButtonItemConfiguration(systemItem: .done, action: #selector(self.doneAction(_:)))
            rightConfiguration.accessibilityLabel = "Done"
        }
 
        let isTableCollectionView: Bool
        if textField.iq.superviewOf(type: UITableView.self) != nil ||
            textField.iq.superviewOf(type: UICollectionView.self) != nil {
            isTableCollectionView = true
        } else {
            isTableCollectionView = false
        }
 
        let previousNextDisplayMode: IQPreviousNextDisplayMode = toolbarConfiguration.previousNextDisplayMode
 
        let havePreviousNext: Bool
        switch previousNextDisplayMode {
        case .default:
            // If the textField is part of UITableView/UICollectionView then we should be exposing previous/next too
            // Because at this time we don't know the previous or next cell if it contains another textField to move.
            if isTableCollectionView {
                havePreviousNext = true
            } else if siblings.count <= 1 {
                //    If only one object is found, then adding only Done button.
                havePreviousNext = false
            } else {
                havePreviousNext = true
            }
        case .alwaysShow:
            havePreviousNext = true
        case .alwaysHide:
            havePreviousNext = false
        }
 
        let placeholderConfig: IQToolbarPlaceholderConfiguration = toolbarConfiguration.placeholderConfiguration
        if havePreviousNext {
            let prevConfiguration: IQBarButtonItemConfiguration
            if let configuration: IQBarButtonItemConfiguration = toolbarConfiguration.previousBarButtonConfiguration {
                configuration.action = #selector(self.previousAction(_:))
                prevConfiguration = configuration
            } else {
                prevConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardPreviousImage),
                                                                 action: #selector(self.previousAction(_:)))
                prevConfiguration.accessibilityLabel = "Previous"
            }
 
            let nextConfiguration: IQBarButtonItemConfiguration
            if let configuration: IQBarButtonItemConfiguration = toolbarConfiguration.nextBarButtonConfiguration {
                configuration.action = #selector(self.nextAction(_:))
                nextConfiguration = configuration
            } else {
                nextConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardNextImage),
                                                                 action: #selector(self.nextAction(_:)))
                nextConfiguration.accessibilityLabel = "Next"
            }
 
            let titleText: String? = placeholderConfig.showPlaceholder ? textField.iq.drawingPlaceholder : nil
            textField.iq.addToolbar(target: self,
                                    previousConfiguration: prevConfiguration,
                                    nextConfiguration: nextConfiguration,
                                    rightConfiguration: rightConfiguration, title: titleText,
                                    titleAccessibilityLabel: placeholderConfig.accessibilityLabel)
 
            // (Bug ID: #78)
            textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag
 
            if isTableCollectionView {
                // (Bug ID: #56)
                // In case of UITableView, the next/previous buttons should always be enabled.
                textField.iq.toolbar.previousBarButton.isEnabled = true
                textField.iq.toolbar.nextBarButton.isEnabled = true
            } else {
                // If firstTextField, then previous should not be enabled.
                textField.iq.toolbar.previousBarButton.isEnabled = (siblings.first != textField)
                // If lastTextField then next should not be enabled.
                textField.iq.toolbar.nextBarButton.isEnabled = (siblings.last != textField)
            }
 
        } else {
 
            let titleText: String? = placeholderConfig.showPlaceholder ? textField.iq.drawingPlaceholder : nil
            textField.iq.addToolbar(target: self, rightConfiguration: rightConfiguration,
                                    title: titleText,
                                    titleAccessibilityLabel: placeholderConfig.accessibilityLabel)
 
            textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag //  (Bug ID: #78)
        }
 
        let toolbar: IQToolbar = textField.iq.toolbar
 
        // Setting toolbar tintColor //  (Enhancement ID: #30)
        if toolbarConfiguration.useTextFieldTintColor {
            toolbar.tintColor = textField.tintColor
        } else {
            toolbar.tintColor = toolbarConfiguration.tintColor
        }
 
        //  Setting toolbar to keyboard.
        if let textFieldView: any UITextInput = textField as? (any UITextInput) {
 
            // Bar style according to keyboard appearance
            switch textFieldView.keyboardAppearance {
 
            case .dark?:
                toolbar.barStyle = .black
                toolbar.barTintColor = nil
            default:
                toolbar.barStyle = .default
                toolbar.barTintColor = toolbarConfiguration.barTintColor
            }
        }
 
        // Setting toolbar title font.   //  (Enhancement ID: #30)
        if toolbarConfiguration.placeholderConfiguration.showPlaceholder,
            !textField.iq.hidePlaceholder {
 
            // Updating placeholder font to toolbar.     //(Bug ID: #148, #272)
            if toolbar.titleBarButton.title == nil ||
                toolbar.titleBarButton.title != textField.iq.drawingPlaceholder {
                toolbar.titleBarButton.title = textField.iq.drawingPlaceholder
            }
 
            // Setting toolbar title font.   //  (Enhancement ID: #30)
            toolbar.titleBarButton.titleFont = toolbarConfiguration.placeholderConfiguration.font
 
            // Setting toolbar title color.   //  (Enhancement ID: #880)
            toolbar.titleBarButton.titleColor = toolbarConfiguration.placeholderConfiguration.color
 
            // Setting toolbar button title color.   //  (Enhancement ID: #880)
            toolbar.titleBarButton.selectableTitleColor = toolbarConfiguration.placeholderConfiguration.buttonColor
 
        } else {
            toolbar.titleBarButton.title = nil
        }
 
        // In case of UITableView (Special), the next/previous buttons has to be refreshed every-time.    (Bug ID: #56)
 
        // If firstTextField, then previous should not be enabled.
        textField.iq.toolbar.previousBarButton.isEnabled = (siblings.first != textField)
 
        // If lastTextField then next should not be enabled.
        textField.iq.toolbar.nextBarButton.isEnabled = (siblings.last != textField)
 
        let elapsedTime: CFTimeInterval = CACurrentMediaTime() - startTime
        showLog("<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
    }
    // swiftlint:enable function_body_length
    // swiftlint:enable cyclomatic_complexity
 
    /** Remove any toolbar if it is IQToolbar. */
    internal func removeToolbarIfRequired() {    //  (Bug ID: #18)
 
        guard let siblings: [UIView] = responderViews(), !siblings.isEmpty else {
            return
        }
 
        showLog(">>>>> \(#function) started >>>>>", indentation: 1)
        let startTime: CFTimeInterval = CACurrentMediaTime()
 
        showLog("Found \(siblings.count) responder sibling(s)")
 
        for view in siblings {
            removeToolbarIfRequired(of: view)
        }
 
        let elapsedTime: CFTimeInterval = CACurrentMediaTime() - startTime
        showLog("<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
    }
 
    /** Remove any toolbar if it is IQToolbar. */
    internal func removeToolbarIfRequired(of view: UIView) {    //  (Bug ID: #18)
 
        guard view.responds(to: #selector(setter: UITextField.inputAccessoryView)),
              let toolbar: IQToolbar = view.inputAccessoryView as? IQToolbar,
              toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
                toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag else {
            return
        }
 
        // setInputAccessoryView: check   (Bug ID: #307)
        if let textField: UITextField = view as? UITextField {
            textField.inputAccessoryView = nil
        } else if let textView: UITextView = view as? UITextView {
            textView.inputAccessoryView = nil
        }
    }
 
    /**    reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
    @objc func reloadInputViews() {
 
        // If enabled then adding toolbar.
        if privateIsEnableAutoToolbar() {
            self.addToolbarIfRequired()
        } else {
            self.removeToolbarIfRequired()
        }
    }
}