swiftuiviewcontrollerfirst-responder

Where to call becomeFirstResponder(), at ViewDidAppear or ViewWillAppear?


What I want:

A textField and a textLabel is included in the tableView. When the tableView is present the textField will be the firstResponder and brings out the keyboard.

Problems I have:

the App is only shows the keyboard if the textField.becomeFirstResponder() is called within viewWillAppear or viewDidLoad (textField and textLabel is not showing at all).

How I fixed it:

The bug is not reproducible when I moved the textField.becomeFirstResponder() call into viewDidAppear

Question:

Am I spouse to call becomeFirstResponder() function inside the viewDidAppear function? otherwise the keyboard will block all the other views

Many Thanks


Solution

  • Think about what viewDidLoad, viewWillAppear, and viewDidAppear mean.

    You need your view to be part of the interface before your text field can summon the keyboard. Only then is the table view actually showing and configured. In other words, at this point the interface has settled down into its actual form, and we are ready to place the keyboard correctly above it.