-
Notifications
You must be signed in to change notification settings - Fork 384
/
Copy pathInputTextFormatter.swift
261 lines (208 loc) · 8.91 KB
/
InputTextFormatter.swift
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
//
// InputTextFormatter.swift
// MullvadVPN
//
// Created by pronebird on 08/04/2020.
// Copyright © 2020 Mullvad VPN AB. All rights reserved.
//
import Foundation
import UIKit
/// A class describing the account token input and caret management.
/// Suitable to be used with `UITextField`.
class InputTextFormatter: NSObject, UITextFieldDelegate, UITextPasteDelegate {
enum AllowedInput {
case numeric, alphanumeric(isUpperCase: Bool)
}
struct Configuration {
/// Allowed characters.
var allowedInput: AllowedInput
/// Separator between groups of characters.
var groupSeparator: Character
/// The size of each group of characters .
var groupSize: UInt8
/// Maximum number of groups of characters allowed.
var maxGroups: UInt8
}
var configuration: Configuration {
didSet {
replace(with: string)
}
}
/// Parsed string
private(set) var string = ""
/// Formatted string
private(set) var formattedString = ""
// Computed caret position
private(set) var caretPosition = 0
init(string: String = "", configuration: Configuration) {
self.configuration = configuration
super.init()
replace(with: string)
}
/// Replace the currently held value with the given string
func replace(with replacementString: String) {
let stringRange = formattedString.startIndex ..< formattedString.endIndex
replaceCharacters(
in: stringRange,
replacementString: replacementString,
emptySelection: false
)
}
/// Replace characters in range maintaining the caret position
/// Note: `emptySelection` hints that text field selection is empty. This is normally
/// the default state unless a text range is selected.
func replaceCharacters(
in range: Range<String.Index>,
replacementString: String,
emptySelection: Bool
) {
var stringRange = range
// Since removing separator alone makes no sense, this computation extends the string range
// to include the digit preceding a separator.
if replacementString.isEmpty, emptySelection, !formattedString.isEmpty {
let precedingDigitIndex = formattedString
.prefix(through: stringRange.lowerBound)
.lastIndex { isAllowed($0) } ?? formattedString.startIndex
stringRange = precedingDigitIndex ..< stringRange.upperBound
}
// Replace the given range within a formatted string
let newString = formattedString.replacingCharacters(in: stringRange, with: replacementString)
// Number of digits within a string
var numDigits = 0
// Insertion location within the input string
let insertionLocation = formattedString.distance(from: formattedString.startIndex, to: stringRange.lowerBound)
// Original caret location based on insertion location + number of characters added
let originalCaretPosition = insertionLocation + replacementString.count
// Computed caret location that will be modified during the loop
var newCaretPosition = originalCaretPosition
// New re-parsed and re-formatted strings
var reparsedString = ""
var reformattedString = ""
for (index, element) in newString.enumerated() {
// Skip disallowed characters
if !isAllowed(element) {
// Adjust the caret position for characters removed before the insertion location
if originalCaretPosition > index {
newCaretPosition -= 1
}
continue
}
// Apply cap on number of groups of characters that can be entered.
if configuration.maxGroups > 0, configuration.groupSize > 0 {
let numGroups = reparsedString.count / Int(configuration.groupSize)
if numGroups >= configuration.maxGroups {
if originalCaretPosition > index {
newCaretPosition = reformattedString.count
}
break
}
}
// Add separator between the groups of digits
if numDigits > 0,
configuration.groupSize > 0,
numDigits % Int(configuration.groupSize) == 0 {
reformattedString.append(configuration.groupSeparator)
if originalCaretPosition > index {
// Adjust the caret position to account for separators added before the
// insertion location
newCaretPosition += 1
}
}
reformattedString.append(element)
reparsedString.append(element)
numDigits += 1
}
if case AllowedInput.alphanumeric(true) = configuration.allowedInput {
reformattedString = reformattedString.uppercased()
}
caretPosition = newCaretPosition
formattedString = reformattedString
string = reparsedString
}
/// Update the text and caret position in the given text field
func updateTextField(_ textField: UITextField) {
updateTextField(textField, notifyDelegate: false)
}
// MARK: - UITextFieldDelegate
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
let emptySelection = textField.selectedTextRange?.isEmpty ?? false
// Certain characters such as a backtick can pass through the textField, and appear as an empty string, with a
// range outside of the boundaries of the `formattedString`. Such characters are ignored.
guard let stringRange = Range(range, in: formattedString) else {
updateTextField(textField, notifyDelegate: true)
return false
}
replaceCharacters(
in: stringRange,
replacementString: string,
emptySelection: emptySelection
)
updateTextField(textField, notifyDelegate: true)
return false
}
// MARK: - UITextPasteDelegate
func textPasteConfigurationSupporting(
_ textPasteConfigurationSupporting: any UITextPasteConfigurationSupporting,
performPasteOf attributedString: NSAttributedString,
to textRange: UITextRange
) -> UITextRange {
guard let textField = textPasteConfigurationSupporting as? UITextField else {
return textRange
}
let location = textField.offset(from: textField.beginningOfDocument, to: textRange.start)
let length = textField.offset(from: textRange.start, to: textRange.end)
let nsRange = NSRange(location: location, length: length)
guard let stringRange = Range(nsRange, in: formattedString) else { return textRange }
replaceCharacters(
in: stringRange,
replacementString: attributedString.string,
emptySelection: textRange.isEmpty
)
updateTextField(textField, notifyDelegate: true)
return caretTextRange(in: textField)!
}
// MARK: - Private
/// A caret position as utf-16 offset compatible for use with `NSString` and `UITextField`.
private var caretPositionUtf16: Int {
let startIndex = formattedString.startIndex
let endIndex = formattedString.index(startIndex, offsetBy: caretPosition)
return formattedString.utf16.distance(from: startIndex, to: endIndex)
}
/// Convert the computed caret position to an empty `UITextRange` within the given text field.
private func caretTextRange(in textField: UITextField) -> UITextRange? {
guard let position = textField.position(
from: textField.beginningOfDocument,
offset: caretPositionUtf16
) else { return nil }
return textField.textRange(from: position, to: position)
}
/// A helper to update the text and caret in the given text field, and optionally post
/// `UITextField.textDidChange` notification.
private func updateTextField(_ textField: UITextField, notifyDelegate: Bool) {
textField.text = formattedString
textField.selectedTextRange = caretTextRange(in: textField)
if notifyDelegate {
Self.notifyTextDidChange(in: textField)
}
}
/// Posts `UITextField.textDidChange` notification.
private class func notifyTextDidChange(in textField: UITextField) {
NotificationCenter.default.post(
name: UITextField.textDidChangeNotification,
object: textField
)
}
private func isAllowed(_ character: Character) -> Bool {
guard character.isASCII else { return false }
switch configuration.allowedInput {
case .numeric:
return character.isNumber
case .alphanumeric:
return character.isLetter || character.isNumber
}
}
}