forked from Rightpoint/FrictionLess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormattableTextField.swift
More file actions
288 lines (233 loc) · 9.5 KB
/
FormattableTextField.swift
File metadata and controls
288 lines (233 loc) · 9.5 KB
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
//
// FormattableTextField.swift
// Raizlabs
//
// Created by Jason Clark on 3/24/17.
//
//
import UIKit
// MARK: - Errors
public enum FormattableTextFieldError: Error {
case invalidInput
}
// MARK: - FormattableTextField
open class FormattableTextField: UITextField {
// MARK: Appearance
public dynamic var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
public dynamic var borderColor: UIColor = .clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
public dynamic var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
// MARK: Initialization
fileprivate let delegateProxy: DelegateProxy
public init(formatter: TextFieldFormatter? = nil) {
self.delegateProxy = DelegateProxy()
super.init(frame: .zero)
self.formatter = formatter
self.delegate = self.delegateProxy
addTarget(delegateProxy, action: #selector(DelegateProxy.editingChanged(textField:)), for: .editingChanged)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: Accessors
extension FormattableTextField {
public var isValid: Bool {
if case ValidationResult.valid = validation {
return true
}
else {
return false
}
}
public var isComplete: Bool {
return formatter?.isComplete(unformattedText) ?? true
}
public var validation: ValidationResult {
return formatter?.validate(unformattedText) ?? .valid
}
public var unformattedText: String {
guard let text = text else { return "" }
return formatter?.removeFormatting(text) ?? text
}
public var formatter: TextFieldFormatter? {
get {
return delegateProxy.formatter
}
set {
delegateProxy.formatter = newValue
}
}
override weak open var delegate: UITextFieldDelegate? {
get {
return delegateProxy.delegate
}
set {
super.delegate = delegateProxy
if !(newValue is DelegateProxy) {
delegateProxy.delegate = newValue
}
}
}
}
// MARK: Methods
public extension FormattableTextField {
/// Programmatically set text and format. Forgo the delegate and validation responder train.
public func setTextAndFormat(text: String) {
guard let formatter = formatter else {
self.text = text
return
}
let event = EditingEvent(oldValue: self.text ?? "",
editRange: self.textRange,
selectedTextRange: self.selectedRange,
editString: text,
newValue: text,
newCursorPosition: text.characters.count)
let formatted = formatter.format(editingEvent: event)
if case .valid(let formattingResult) = formatted {
let formattedText: String
if let result = formattingResult {
switch result {
case .text(let string): formattedText = string
case .textAndCursor(let string, _): formattedText = string
}
}
else {
formattedText = text
}
self.text = formattedText
}
}
/// Simulate the manual entry of text in an optional subrange. Format, validate, and report up the responder chain.
public func simulateInput(text: String, range: NSRange? = nil) {
let editRange = range ?? self.textRange
_ = delegateProxy.textField(self, shouldChangeCharactersIn: editRange, replacementString: text)
}
}
// MARK: Overrides
extension FormattableTextField {
override open func deleteBackward() {
super.deleteBackward()
if text?.characters.count == 0 {
(delegate as? FormattableTextFieldDelegate)?.textFieldShouldNavigateBackwards(self)
}
}
}
// MARK: Delegate Proxy Private Implementation
fileprivate extension FormattableTextField {
class DelegateProxy: NSObject, UITextFieldDelegate {
weak var delegate: UITextFieldDelegate?
var formatter: TextFieldFormatter?
}
}
extension FormattableTextField.DelegateProxy {
@objc func editingChanged(textField: UITextField) {
guard let textField = textField as? FormattableTextField else {
fatalError("")
}
(delegate as? FormattableTextFieldDelegate)?.editingChanged(textField: textField)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let delegateResponse = delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true
guard let formatter = formatter, delegateResponse == true else {
return delegateResponse
}
guard let textField = textField as? FormattableTextField else {
fatalError("")
}
guard formatter.containsValidChars(text: string) else {
(delegate as? FormattableTextFieldDelegate)?.textField(textField, invalidInput: FormattableTextFieldError.invalidInput)
return false
}
//if user is inserting text at the end of a complete text field, alert delegate to potentially forward the input
if range.location == textField.text?.characters.count && string.characters.count > 0 {
if formatter.isComplete(textField.unformattedText) {
(delegate as? FormattableTextFieldDelegate)?.textField(textField, didOverflowInput: string)
return false
}
}
if let indexRange = textField.text?.range(fromNSRange: range) {
let newText = textField.text?.replacingCharacters(in: indexRange, with: string)
let newRange = range.location + string.characters.count
let event = EditingEvent(oldValue: textField.text ?? "",
editRange: range,
selectedTextRange: textField.selectedRange,
editString: string,
newValue: newText ?? "",
newCursorPosition: newRange)
//Adjust the editing event for
// 1. deleting a single formatting charaacter
var adjustedEdit = formatter.handleDeletionOfFormatting(editingEvent: event)
// 2. optionally removing all characters trailing a delte
adjustedEdit = formatter.removeCharactersTrailingDelete(textField: textField, editingEvent: adjustedEdit)
let value = formatter.removeFormatting(adjustedEdit.newValue)
adjustedEdit.newCursorPosition = adjustedEdit.cursorPosition(inFormattedText: value, withinSet: formatter.inputCharacterSet)
adjustedEdit.newValue = value
//then hand the edit to the formatter
let result = formatter.format(editingEvent: adjustedEdit)
let formattedText: String
let cursorPosition: Int
switch result {
case .valid(let formattingResult):
switch formattingResult {
case .none:
formattedText = adjustedEdit.newValue
cursorPosition = adjustedEdit.newCursorPosition
case .some(.text(let string)):
formattedText = string
cursorPosition = adjustedEdit.cursorPosition(inFormattedText: string, withinSet: formatter.inputCharacterSet)
case .some(.textAndCursor(let string, let cursor)):
formattedText = string
cursorPosition = cursor
}
textField.text = formattedText
textField.selectedTextRange = textField.textRange(cursorOffset: cursorPosition)
textField.sendActions(for: .editingChanged)
case .invalid(let error):
(delegate as? FormattableTextFieldDelegate)?.textField(textField, invalidInput: error)
return false
}
}
return false
}
}
// MARK: Delegate Proxy Forwarding
extension FormattableTextField.DelegateProxy {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return delegate?.textFieldShouldBeginEditing?(textField) ?? true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
delegate?.textFieldDidBeginEditing?(textField)
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return delegate?.textFieldShouldEndEditing?(textField) ?? true
}
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
guard let delegate = delegate else { return }
if delegate.responds(to: #selector(UITextFieldDelegate.textFieldDidEndEditing(_:reason:))) {
delegate.textFieldDidEndEditing?(textField, reason: reason)
}
else {
delegate.textFieldDidEndEditing?(textField)
}
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return delegate?.textFieldShouldClear?(textField) ?? true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return delegate?.textFieldShouldReturn?(textField) ?? true
}
}