@@ -59,20 +59,24 @@ public struct ResponsiveTextField {
59
59
/// If this is not set, the textfield delegate will indicate that the return key is not handled.
60
60
var handleReturn : ( ( ) -> Void ) ?
61
61
62
+ var shouldChange : ( ( String , String ) -> Bool ) ?
63
+
62
64
public init (
63
65
placeholder: String ,
64
66
text: Binding < String > ,
65
67
isEditing: Binding < Bool > ,
66
68
isSecure: Bool = false ,
67
69
configuration: Configuration = . empty,
68
- handleReturn: ( ( ) -> Void ) ? = nil
70
+ handleReturn: ( ( ) -> Void ) ? = nil ,
71
+ shouldChange: ( ( String , String ) -> Bool ) ? = nil
69
72
) {
70
73
self . placeholder = placeholder
71
74
self . text = text
72
75
self . isEditing = isEditing
73
76
self . isSecure = isSecure
74
77
self . configuration = configuration
75
78
self . handleReturn = handleReturn
79
+ self . shouldChange = shouldChange
76
80
}
77
81
}
78
82
@@ -155,6 +159,22 @@ extension ResponsiveTextField: UIViewRepresentable {
155
159
return false
156
160
}
157
161
162
+ public func textField(
163
+ _ textField: UITextField ,
164
+ shouldChangeCharactersIn range: NSRange ,
165
+ replacementString string: String
166
+ ) -> Bool {
167
+ if let shouldChange = parent. shouldChange {
168
+ let currentText = textField. text ?? " "
169
+ guard let newRange = Range ( range, in: currentText) else {
170
+ return false // when would this conversion fail?
171
+ }
172
+ let newText = currentText. replacingCharacters ( in: newRange, with: string)
173
+ return shouldChange ( currentText, newText)
174
+ }
175
+ return true
176
+ }
177
+
158
178
@objc func textFieldTextChanged( _ textField: UITextField ) {
159
179
self . text = textField. text ?? " "
160
180
}
@@ -260,7 +280,8 @@ struct ResponsiveTextField_Previews: PreviewProvider {
260
280
placeholder: " Placeholder " ,
261
281
text: $text,
262
282
isEditing: $isEditing,
263
- configuration: configuration
283
+ configuration: configuration,
284
+ shouldChange: { $1. count <= 10 }
264
285
)
265
286
. fixedSize ( horizontal: false , vertical: true )
266
287
. padding ( )
0 commit comments