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.
Asked
Active
Viewed 4.5k times
3 Answers
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
-
2IMHO, it's best to put this in `viewDidAppear`. The visual effect is nicer. – amb Feb 26 '13 at 13:50
-
2This 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