61

I have a very simple table and when tocuh a cell it opens a new view with one UITextfield. All I want is that the keyboard will automatically opens, without the user have to touch the UITextfield.

Its all done in Interface Builder, so I am not sure how I do this. I guess I need to set the focus at some point ?

Thanks

eemceebee
  • 2,656
  • 9
  • 39
  • 49

4 Answers4

139

To cause the keyboard to show up immediately you'll need to set the text field as the first responder using the following line:

[textField becomeFirstResponder];

You may want to place this in the viewDidAppear: method.

jessecurry
  • 22,068
  • 8
  • 52
  • 44
  • 30
    I recommend -viewDidAppear:, since this generates animations. Generating animations in -viewWillAppear can lead to graphic artifacts, since you're not on the screen yet. Since you almost certainly want it every time you come on screen, -viewDidLoad is likely redundant (it happens every time the view is loaded from disk, which is somewhat unpredictable, so isn't a good place for visual effects). – Rob Napier Feb 16 '10 at 14:27
  • Do you need to import the ```UITextViewDelegate``` delegate when doing this and then connect it to the delegate in IB? – Supertecnoboff May 31 '15 at 08:37
  • 3
    for swift 3 : `override func viewDidAppear(_ animated: Bool) { textField.becomeFirstResponder() }` – emy Sep 17 '17 at 15:32
13

Swift 3 & 4:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    textField.becomeFirstResponder()
}
Nico S.
  • 3,056
  • 1
  • 30
  • 64
1
override func viewDidLoad() {
    super.viewDidLoad()
    textField.becomeFirstResponder()
}
Shubham Goel
  • 1,962
  • 17
  • 25
0

Prefer adding the first responder on the main thread -

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

This will come in handy when the view controller view is added as a subview.

Yash
  • 227
  • 1
  • 4