2

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
            }
        }
    }
}

ydstmw
  • 61
  • 1
  • 4
  • Did you get the solution? – salih Jun 12 '21 at 15:25
  • Just got it like, right now. The issue was due to a global approach I had while initializing my views. Infulenced by a lot of YouTube videos (I am a beginner), I was merging my views and view models togethers, resulting in triple init sometimes during a view display...as well as these inputs not being autofocused. Since then, I have split my architecture into: view model + view, and as a result cleaned my inits. The same code I have shared is working well. My answer may be confused however I have no idea about your configuration. Let's say that the answer is in your init. Good Luck. – ydstmw Jun 12 '21 at 18:26

0 Answers0