How do I give a UITextView focus programmatically?

IosObjective CCocoa TouchUikit

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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];

Solution 2 - Ios

Swift:

textView.becomeFirstResponder()

Solution 3 - Ios

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]; }

Solution 4 - Ios

[textView becomeFirstResponder];

Solution 5 - Ios

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

Solution 6 - Ios

On Xamarin Forms Custom Render:

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

        if (Control != null)
        {
            Control.BecomeFirstResponder();
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMeroonView Question on Stackoverflow
Solution 1 - IosAlex RozanskiView Answer on Stackoverflow
Solution 2 - IosEsqarrouthView Answer on Stackoverflow
Solution 3 - IosErikView Answer on Stackoverflow
Solution 4 - IosCorey FloydView Answer on Stackoverflow
Solution 5 - Iosuser8851874View Answer on Stackoverflow
Solution 6 - IosIgor MonteiroView Answer on Stackoverflow