How to programmatically adjust focus of a UITextView?

So, I want to create a modal view controller that has a UITextView, and I want the keyboard to pop up automatically, and the UITextView has focus.

I found a way to do this by following these steps:

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

It just seems hacked to me, is there any other way?

+51
ios objective-c cocoa-touch uikit
Jun 12 '09 at 17:33
source share
5 answers

Since UITextView inherits from UIResponder (indirectly, it inherits from UIScrollView , which inherits from UIView , which then inherits from UIResponder ), you can call the -becomeFirstResponder method in your text field, which will make it become the first responder and start editing:

 [textView becomeFirstResponder]; 
+144
Jun 12 '09 at 18:03
source share

Swift:

 textView.becomeFirstResponder() 
+13
Aug 01 '15 at 13:19
source share

It looks somewhat hacky.

Cocoa Touch's terminology for “with focus” is the “first responder,” and the UITextView will display its keyboards when they are the first responder. I can come up with several methods to make UITextView the first responder, but the easiest is probably your viewWillAppear or viewDidAppear control method:

 - (void) viewWillAppear: (BOOL) animated
 {

     [myTextView becomeFirstResponder];

     [super viewWillAppear: animated];
 }
+11
Jun 12 '09 at 18:06
source share
 [textView becomeFirstResponder]; 
+7
Jun 12 '09 at 21:02
source share

If you want the focus to be that specific TextView when loading the ViewController, you can put textView.becomeFirstResponder () in the OverDend ViewDidLoad function, as shown below:

  override func viewDidLoad() { super.viewDidLoad() textView.becomeFirstResponder() } 

I believe this works without errors

0
Nov 20 '17 at 15:59
source share



All Articles