You can find a quick wrapper for the UIKit TextField.
swift
struct CustomTextField: UIViewRepresentable {
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
var onCommit: (_ value: String) -> Void
var didBecomeFirstResponder = false
init(text: Binding<String>, onCommit: @escaping (_ value: String) -> Void) {
_text = text
self.onCommit = onCommit
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
onCommit(textField.text ?? "")
return true
}
}
@Binding var text: String
var onCommit: (_ value: String) -> Void
var isFirstResponder: Bool = false
func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.delegate = context.coordinator
return textField
}
func makeCoordinator() -> CustomTextField.Coordinator {
return Coordinator(text: $text, onCommit: onCommit)
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
uiView.text = text
if isFirstResponder && !context.coordinator.didBecomeFirstResponder {
uiView.becomeFirstResponder()
context.coordinator.didBecomeFirstResponder = true
}
}
}
You can further customise it with what you need.
Post
Replies
Boosts
Views
Activity
The issue was caused by this error Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/ctorge/Desktop/quote/Quote/Services/Utils/UI/Modifiers.swift, line 97. It would be nice to get this kind of errors in the SwiftUI Preview Diagnosis.
Hi! Thanks for your reply!
Indeed the issue was because Color.mediumGray. Thank you!