Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus to an iOS text field?

How do you programmatically set focus to some UITextField in iOS?

When you tap on a textfield, the keyboard pops up to begin editing the textfield.

How can you give focus to a textfield and bring up the keyboard without requiring the user to tap on the textfield?

like image 582
Ravi kumar Avatar asked Sep 23 '11 07:09

Ravi kumar


People also ask

How do you set focus on textfield?

To give focus to a text field as soon as it's visible, use the autofocus property. TextField( autofocus: true, );

What is a text field on Iphone?

A text field is a rectangular area in which people enter or edit small, specific pieces of text.

How do I remove focus from textfield?

To close keyboard / to hide the keyboard you need to simply remove focus from textfield & thus it automatically dismiss the keyboard. So to remove focus from textfield you just need to run FocusScope unfocus, when user tap outside the textfield.


1 Answers

Make the textField the first responder; this will also popup the keyboard:

[self.textField becomeFirstResponder]; 

And just some more typical example code which may help someone,

in your storyboard, click on one of the text fields, and set the outlets-delegate to be the class in question. In that class, in the .h file make sure that you declare that it is a UITextFieldDelegate

@interface Login : UIViewController <UITextFieldDelegate> 

Then in the .m file, you could have this for example...

-(BOOL)textFieldShouldReturn:(UITextField *)textField {     if ( textField == self.loginEmail ) { [self.loginPassword becomeFirstResponder]; }     if ( textField == self.loginPassword ) { [self yourLoginRoutine]; return YES; }     return YES; } 

When a user clicks the "Next" button on the virtual keyboard - on the 'email' field - it will correctly move you to the password field. When a user clicks the "Next" button on the virtual keyboard - on the 'password' field - it will correctly call your yourLoginRoutine.

(On the storyboard, on the attributes inspector, notice that you can select the text you want on the Return key ... here "Next" would work nicely on the email field and "Done" would work nicely on the password field.)

like image 74
rckoenes Avatar answered Oct 07 '22 01:10

rckoenes