41

I have a UITextField that I want to set into editing mode (keyboard on screen and cursor in text field box) programatically. I know that the user will be in editing mode when this view appears onscreen, so I want to save the user from having to tap the text field.

The "editing" property of a UITextField is read only - so that doesn't work. Is there a way to set the UITextField into editing mode, with a keyboard onscreen, programmatically?

xlm
  • 6,854
  • 14
  • 53
  • 55
Don Wilson
  • 2,303
  • 3
  • 26
  • 34

3 Answers3

79

Call becomeFirstResponder on the UITextField.

Related question: How do I show the keyboard by default in UITextView?

Community
  • 1
  • 1
Tyler
  • 28,498
  • 11
  • 90
  • 106
  • I found this to be unreliable unless I made sure to run it in the main thread: dispatch_async( dispatch_get_main_queue(), ^{[textView becomeFirstResponder];}); – Ian Ollmann Feb 13 '22 at 18:09
28

You have to call [textField becomeFirstResponder];

Jakub
  • 13,712
  • 17
  • 82
  • 139
Thomas Huber
  • 1,282
  • 1
  • 13
  • 23
12

Indeed call [textField becomeFirstResponder] in Obj-C or textField.becomeFirstResponder() in Swift.

However, make sure you call this in the viewDidAppear and not in the viewDidLoad to prevent strange behaviour (see: When set UITextField as FirstResponder programmatically, cause some weird actions on text editing).

Community
  • 1
  • 1
Tom
  • 874
  • 7
  • 13