Swift: Become First Responder on UITextField Not Working?

blee908 picture blee908 · Aug 17, 2014 · Viewed 50.5k times · Source

I've created a custom UIViewController with one UITextField on Storyboard. On viewDidLoad, I set the UITextFIeld to becomeFirstResponder, nothing happened (no keyboards popped up).

I then tried calling resignFirstResponder(), but it returned false. Next I tried to find who the first responder is through looping all the subviews using the code over @ Get the current first responder without using a private API. It turns out none of the sub views are the first responder.

My ViewController in storyboard

enter image description here

My Code

class BLTestViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var tf: UITextField

    override func viewDidLoad() {
        super.viewDidLoad()

        tf.delegate = self
        tf.becomeFirstResponder()
        // Do any additional setup after loading the view.
    }
}

As simple as it gets...WHY ISN'T THE KEYBOARD COMING UP!!! One thing I do have on is auto layout, but I'm not sure if that affects the keyboard popping up.

Answer

Methawin Intharakham picture Methawin Intharakham · Sep 5, 2018

Swift 4 it worked for me
try it

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    textView.becomeFirstResponder()
    
}