66

How can I programmatically assign focus to a specific UITextField in a view? I have several fields and on view display, I'd like to put the cursor on a specific field, not the first one at top.

phunehehe
  • 8,618
  • 7
  • 49
  • 79
Robin Jamieson
  • 1,425
  • 2
  • 19
  • 27

3 Answers3

151

Try doing this in viewWillAppear:

[desiredField becomeFirstResponder];

By making the field the first responder, it have focus and the keyboard will be displayed.

Alex Rozanski
  • 37,815
  • 10
  • 68
  • 69
Alexi Groove
  • 6,646
  • 12
  • 47
  • 54
  • Hi, are you sure it works on viewWillAppear? I tried it, it didn't work. Instead I put it on viewDidLoad, and it works. – Mickey Cheong Apr 02 '11 at 15:34
  • 2
    IMHO, it's best to put this in `viewDidAppear`. The visual effect is nicer. – amb Feb 26 '13 at 13:50
  • 2
    This is the code in Swift for those who need it. `desiredField.becomeFirstResponder()` – Anh Pham Dec 08 '17 at 03:38
  • @MickeyCheong Don't forget to call `super.viewDidAppear(animated)` inside of the overridden viewDidAppear. It won't work without it. – Chad Parker May 01 '18 at 19:20
5

Set the first responder for your view to be the text field. This can be done in IB.

Dan Lorenc
  • 5,376
  • 1
  • 23
  • 34
3

In swift:

desiredField.becomeFirstResponder()
Menno
  • 1,232
  • 12
  • 23