Last active
July 22, 2021 07:45
-
-
Save graylikeme/84cc8538b452d9305593843b12316304 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 NVTextField<V: Hashable>: UIViewRepresentable { | |
@Binding var text: String | |
var id: V | |
@Binding var firstResponder: V? | |
private var onReturn: () -> Void | |
init(text: Binding<String>, id: V, firstResponder: Binding<V?>, onReturn: @escaping (() -> Void) = {}) { | |
self.id = id | |
_text = text | |
_firstResponder = firstResponder | |
self.onReturn = onReturn | |
} | |
func makeCoordinator() -> NVTextFieldCoordinator { | |
NVTextFieldCoordinator(text: $text, | |
onStartEditing: startedEditing, | |
onEndEditing: finishedEditing, | |
onReturnTap: returnTap) | |
} | |
func makeUIView(context: Context) -> UITextField { | |
let textField = UITextField() | |
textField.delegate = context.coordinator | |
setProperties(textField: textField) | |
textField.addTarget(context.coordinator, action: #selector(Coordinator.textFieldDidChange(_:)), for: .editingChanged) | |
return textField | |
} | |
func updateUIView(_ textField: UITextField, context: Context) { | |
textField.delegate = context.coordinator | |
setProperties(textField: textField) | |
if id == firstResponder, textField.isFirstResponder == false { | |
DispatchQueue.main.async { | |
textField.becomeFirstResponder() | |
} | |
} | |
} | |
func setProperties(textField: UITextField) { | |
textField.setContentHuggingPriority(.defaultHigh, for: .vertical) | |
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) | |
} | |
func startedEditing() { | |
if id != firstResponder { | |
firstResponder = id | |
} | |
} | |
func finishedEditing() { | |
guard id == firstResponder else { return } | |
firstResponder = nil | |
} | |
func returnTap() { | |
self.onReturn() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment