Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Become First Responder on UITextField Not Working?

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.

like image 314
blee908 Avatar asked Aug 17 '14 21:08

blee908


People also ask

What is become first responder Swift?

The first responder is whatever control is currently ready to respond to actions. In UIKit this is usually the control that has activated the keyboard and is receiving input.

What is first responder in Xcode?

The first responder is usually the first object in a responder chain to receive an event or action message. In most cases, the first responder is a view object that the user selects or activates with the mouse or keyboard.


2 Answers

Swift 4 it worked for me
try it

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    textView.becomeFirstResponder()
    
}
like image 50
Methawin Intharakham Avatar answered Sep 22 '22 12:09

Methawin Intharakham


I just tested it with a textfield by calling self.tf.becomeFirstResponder() indside viewDidLoad() function and its working absolutely fine. You'll need to toggle your keyboard by pressing command + K as nflacco just pointed out and disable the hardware keyboard in the simulator as:

  1. iOS Simulator -> Hardware -> Keyboard
  2. Uncheck "Connect Hardware Keyboard"
like image 39
4aRk Kn1gh7 Avatar answered Sep 19 '22 12:09

4aRk Kn1gh7