Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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