68

So I want to bring in a modal view controller that has a UITextView in it and I want the keyboard to automatically popup and the UITextView have focus.

I found a way to accomplish this by doing the following:

textView.editable = YES;
textView.editable = NO;

This just seems hacky to me, is there another way?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Meroon
  • 3,458
  • 4
  • 25
  • 29

6 Answers6

168

Since UITextView inherits from UIResponder (indirectly, it actually inherits from UIScrollView, which inherits from UIView which then inherits from UIResponder) you can call the -becomeFirstResponder method on your text field, which will cause it to become the first responder and begin editing:

[textView becomeFirstResponder];
Alex Rozanski
  • 37,815
  • 10
  • 68
  • 69
32

Swift:

textView.becomeFirstResponder()
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
12

That does seem somewhat hackish.

The Cocoa Touch terminology for 'having focus' is 'first responder' and UITextViews will display their keyboards when they are the first responder. I can think of several techniques to make the UITextView become the first responder, but the easiest is probably in your view controller's viewWillAppear or viewDidAppear methods:

- (void)viewWillAppear:(BOOL)animated
{

    [myTextView becomeFirstResponder];

    [super viewWillAppear:animated];
}
prairiedogg
  • 6,323
  • 8
  • 44
  • 52
Erik
  • 898
  • 8
  • 20
7
[textView becomeFirstResponder];
Corey Floyd
  • 25,929
  • 31
  • 126
  • 154
1

When you want the focus to be that particular TextView on loading a ViewController, you can place the textView.becomeFirstResponder() in the ViewDidLoad overrode func as below:

 override func viewDidLoad() {
    super.viewDidLoad()

textView.becomeFirstResponder()

}

I find this works without any errors

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
-1

On Xamarin Forms Custom Render:

   protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.BecomeFirstResponder();
        }
    }
Igor Monteiro
  • 933
  • 1
  • 11
  • 29