Following the tons of explanations found on this Stackoverflow post, I have been able to make things work correctly (Xcode 12.5, iOS14) and I am grateful for your help.
One issue though: I am facing a scenario where a sheet has an other sheet as parent. And both are displaying a firstResponderTextField.
While for the parent sheet, the expected behavior is working fine and the keyboard shows up, displaying the children sheet doesn't seem to match the uiView.window != nil, !context.coordinator.becameFirstResponder
condition. The keyboard doesn't show up for the children sheet.
As for now, I can't figure out why the presence of uiView.window != nil
in the condition doesn't match this situation too.
Here is the code, thank you for your time.
struct firstResponderTextField: UIViewRepresentable {
@Binding var text: String
let placeholder: String
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
var becameFirstResponder = false
init(text: Binding<String>) {
self._text = text
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: Context) -> some UIView {
let textField = UITextField()
textField.delegate = context.coordinator
textField.placeholder = placeholder
return textField
}
func updateUIView(_ uiView: UIViewType, context: Context) {
if uiView.window != nil, !context.coordinator.becameFirstResponder {
DispatchQueue.main.async {
uiView.becomeFirstResponder()
context.coordinator.becameFirstResponder = true
}
}
}
}