40

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
  • 5,564
  • 13
  • 48
  • 52
Don Wilson
  • 2,283
  • 2
  • 26
  • 34

3 Answers3

78

Call becomeFirstResponder on the UITextField.

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

Community
  • 1
  • 1
Tyler
  • 28,060
  • 11
  • 85
  • 105
  • 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,281
  • 14
  • 80
  • 136
Thomas Huber
  • 1,262
  • 1
  • 13
  • 22
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