Last active
August 13, 2020 19:20
-
-
Save rnapier/bd3a9a5949fe809f7cd9568d85b3e281 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct LengthLimitedTextField: UIViewRepresentable { | |
var title: String | |
@Binding var text: String | |
var maxLength: Int | |
var onCommit: () -> Void | |
init(_ title: String, text: Binding<String>, maxLength: Int = 255, onCommit: @escaping () -> Void) { | |
self.title = title | |
self._text = text | |
self.maxLength = maxLength | |
self.onCommit = onCommit | |
} | |
func makeUIView(context: UIViewRepresentableContext<LengthLimitedTextField>) -> UITextField { | |
let textField = UITextField() | |
textField.font = UIFont.preferredFont(forTextStyle: .caption1) | |
textField.textColor = .lightGray | |
textField.delegate = context.coordinator | |
textField.placeholder = title | |
textField.setContentHuggingPriority(.defaultHigh, for: .vertical) | |
textField.setContentHuggingPriority(.defaultLow, for: .horizontal) | |
return textField | |
} | |
func updateUIView(_ uiView: UITextField, context: Context) { | |
uiView.text = text | |
} | |
func makeCoordinator() -> LengthLimitedTextFieldCoordinator { | |
return LengthLimitedTextFieldCoordinator($text, maxLength: maxLength, onCommit: onCommit) | |
} | |
} | |
class LengthLimitedTextFieldCoordinator: NSObject { | |
@Binding var text: String | |
let maxLength: Int | |
let onCommit: () -> Void | |
init(_ text: Binding<String>, maxLength: Int, onCommit: @escaping () -> Void) { | |
self._text = text | |
self.maxLength = maxLength | |
self.onCommit = onCommit | |
} | |
} | |
extension LengthLimitedTextFieldCoordinator: UITextFieldDelegate { | |
func textField(_ textField: UITextField, | |
shouldChangeCharactersIn range: NSRange, | |
replacementString string: String) -> Bool { | |
guard let currentText = textField.text else { return false } | |
var proposedText = currentText | |
proposedText.replaceSubrange(Range(range, in: currentText)!, with: string) | |
if proposedText.count > maxLength { | |
return false | |
} | |
text = proposedText | |
return true | |
} | |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { | |
onCommit() | |
textField.resignFirstResponder() | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment