Skip to content

Commit 9359b47

Browse files
committed
Add support for conditional text changes
1 parent 6a9bba4 commit 9359b47

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

Package.resolved

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"object": {
3+
"pins": [
4+
{
5+
"package": "SnapshotTesting",
6+
"repositoryURL": "https://github.com/pointfreeco/swift-snapshot-testing.git",
7+
"state": {
8+
"branch": null,
9+
"revision": "c466812aa2e22898f27557e2e780d3aad7a27203",
10+
"version": "1.8.2"
11+
}
12+
}
13+
]
14+
},
15+
"version": 1
16+
}

Sources/ResponsiveTextField/ResponsiveTextField.swift

+23-2
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)