@@ -59,20 +59,24 @@ public struct ResponsiveTextField {
5959 /// If this is not set, the textfield delegate will indicate that the return key is not handled.
6060 var handleReturn : ( ( ) -> Void ) ?
6161
62+ var shouldChange : ( ( String , String ) -> Bool ) ?
63+
6264 public init (
6365 placeholder: String ,
6466 text: Binding < String > ,
6567 isEditing: Binding < Bool > ,
6668 isSecure: Bool = false ,
6769 configuration: Configuration = . empty,
68- handleReturn: ( ( ) -> Void ) ? = nil
70+ handleReturn: ( ( ) -> Void ) ? = nil ,
71+ shouldChange: ( ( String , String ) -> Bool ) ? = nil
6972 ) {
7073 self . placeholder = placeholder
7174 self . text = text
7275 self . isEditing = isEditing
7376 self . isSecure = isSecure
7477 self . configuration = configuration
7578 self . handleReturn = handleReturn
79+ self . shouldChange = shouldChange
7680 }
7781}
7882
@@ -155,6 +159,22 @@ extension ResponsiveTextField: UIViewRepresentable {
155159 return false
156160 }
157161
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+
158178 @objc func textFieldTextChanged( _ textField: UITextField ) {
159179 self . text = textField. text ?? " "
160180 }
@@ -260,7 +280,8 @@ struct ResponsiveTextField_Previews: PreviewProvider {
260280 placeholder: " Placeholder " ,
261281 text: $text,
262282 isEditing: $isEditing,
263- configuration: configuration
283+ configuration: configuration,
284+ shouldChange: { $1. count <= 10 }
264285 )
265286 . fixedSize ( horizontal: false , vertical: true )
266287 . padding ( )
0 commit comments