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?
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.)
For changing focus on the fly:
[yourTextField becomeFirstResponder];
For Swift, you can use:
theTextFieldYouWant.becomeFirstResponder()
Related
I'd like to achieve the following behaviour of a single UITextField and the keyboard:
when the view has loaded UITextField becomes first responder and the keyboard opens (so far so good):
- (void)viewDidLoad
{
[self.editField becomeFirstResponder];
self.editField.delegate = self;
}
Now user inputs some text and presses the return key. That text is added to the data source in the following method:
- (IBAction)didEndOnExit:(id)sender {
//add self.editField.text to data source
}
Now after the return key is pressed and the above UITextField's method gets called and executed I would like the UITextField to clear, the cursor to be placed and be visible at the beginning of the text field and the keyboard not to hide so that new item could be entered in the textfield and added to the data source.
This is how I return to the previous view in the app (using a button):
- (IBAction)backButtonPressed:(id)sender {
[self dismissViewControllerAnimated:NO completion:^{}];
}
I tried playing with UITextFieldDelegate's methods and UITextField's becomeFirstResponder and resign FirstResponder, but am unable to achieve the above described behaviour. I've seen posts here on Stack Overflow about using consecutive UITextField's to enter data, but not to use the same UITextField time and again.
You should override the below mentioned method and do whatever you want and showing the keyboard too.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
Have a try :)
While dismissing view controller all other code executions freezes when (view controller is being dismissed).
Use some delay (performselectorafterdelay). or
completionhandler of dismissingviewcontroller for executing your code when viewcontroller is being dismissing and
Also execute code on main Thread which includes UI changes or updates
after saved your data.. you have to make the uitextfield to be nil... like self.editField.text = nil. then you can call [self.editfield becomesfirstresponder].. after you will add more items to array or else anything everytime the field should be nil after you added..
From the Doc
Return Value: YES if the text field should implement its default
behavior for the return button; otherwise, NO.
For EX - Use the Delegate of UITextField :
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
//add self.editField.text to data source
textField.text = #"";
return NO; // This will do your need
}
Because I used UITextField's action method - (IBAction)didEndOnExit:(id)sender the keyboard always got closed. Apparently that method makes the UITextField resign from being first responder. Instead of adding data to data source in that method, it can be added in the delegates's method - (BOOL)textFieldShouldReturn:(UITextField *)textField and so the keyboard won't close.
I got 2 textField and when the user types something in, and pushes the return button or back button on my navigation controller, that it saves the textFields. I've already tried this:
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
NSLog(#"textFieldShouldEndEditing");
return YES;
}
but this doesn't print out anything. The names of my two textFields are self.CellOne.textField and self.CellTwo.textField and I've also added the <UITextFieldDelegate> delegate in my class. What I actually want is whenever the foces goes off the textFields, it needs to be saved.
my objective simply to save text on UITextField after user click done button on keyboard. I could either do this in extFieldShouldReturn or textFieldDidEndEditing: does it make any difference ? or there a better approach ?
Thanks!!
textFieldShouldReturn is only called if the user presses the return key. If the keyboard is dismissed due to some other reason such as the user selecting another field, or switching views to another screen, it won't be but textFieldDidEndEditing will be.
The best approach is to use textFieldShouldReturn to resign the responder (hide the keyboard) like this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//hide the keyboard
[textField resignFirstResponder];
//return NO or YES, it doesn't matter
return YES;
}
When the keyboard closes, textFieldDidEndEditing will be called. You can then use textFieldDidEndEditing to do something with the text:
- (BOOL)textFieldDidEndEditing:(UITextField *)textField
{
//do something with the text
}
But if you actually want to perform the action only when the user explicitly presses the "go" or "send" or "search" (or whatever) button on the keyboard, then you should put that handler in the textFieldShouldReturn method instead, like this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//hide the keyboard
[textField resignFirstResponder];
//submit my form
[self submitFormActionOrWhatever];
//return NO or YES, it doesn't matter
return YES;
}
I have an UITextField in a MyCustomUIView class and when the UITextField loses focus, I'd like to hide the field and show something else in place.
The delegate for the UITextField is set to MyCustomUIView via IB and I also have 'Did End On Exit' and 'Editing Did End' events pointing to an IBAction method within MyCustomUIView.
#interface MyCustomUIView : UIView {
IBOutlet UITextField *myTextField;
}
-(IBAction)textFieldLostFocus:(UITextField *)textField;
#end
However, neither of these events seem to get fired when the UITextField loses focus. How do you trap/look for this event?
The delegate for the UITextField is set as MyCustomUIView so I am receiving textFieldShouldReturn message to dismiss the keyboard when done.
But what I'm also interested in is figuring when the user presses some other area on the screen (say another control or just blank area) and the text field has lost focus.
Try using delegate for the following method:
- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
NSLog(#"Lost Focus for content: %#", textField.text);
return YES;
}
That worked for me.
I believe you need to designate your view as a UITextField delegate like so:
#interface MyCustomUIView : UIView <UITextFieldDelegate> {
As an added bonus, this is how you get the keyboard to go away when they press the "done" or return buttons, depending on how you have set that property:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
//This line dismisses the keyboard.
[theTextField resignFirstResponder];
//Your view manipulation here if you moved the view up due to the keyboard etc.
return YES;
}
The problem with the resignFirstResponder solution solely is, that it can only be triggered by an explicit keyboard or UITextField event.
I was also looking for a "lost focus event" to hide the keyboard, if somewhere outside the textfield was tapped on.
The only close and practical "solution" I came across is, to disable interactions for other views until the user is finished with the editing (hitting done/return on the keyboard) but still to be able to jump between the textfields to make corrections without the need of sliding out and in the keyboard everytime.
The following snippet maybe useful to someone, who wants to do the same thing:
// disable all views but textfields
// assign this action to all textfields in IB for the event "Editing Did Begin"
-(IBAction) lockKeyboard : (id) sender {
for(UIView *v in [(UIView*)sender superview].subviews)
if (![v isKindOfClass:[UITextField class]]) v.userInteractionEnabled = NO;
}
// reenable interactions
// assign this action to all textfields in IB for the event "Did End On Exit"
-(IBAction) disMissKeyboard : (id) sender {
[(UIResponder*)sender resignFirstResponder]; // hide keyboard
for(UIView *v in [(UIView*)sender superview].subviews)
v.userInteractionEnabled = YES;
}
You might have to subclass the UITextField and override resignFirstResponder. resignFirstResponder will be called just as the text field is losing focus.
i think you have implemented UIKeyboardDidHideNotification and in this event you
use code like
[theTextField resignFirstResponder];
remove this code.
also same code write in textFieldShouldReturn method. this also lost focus.
In Swift, you need to implement the UITextFieldDelegate to your ViewController and implement the method textFieldDidEndEditing from the delegate:
class ViewController: UIViewController, UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
// will be called when the text field loses their focus
}
}
Then you need to asign the delegate of your textField:
textField.delegate = self
For those struggling with this in Swift. We add a gesture recognizer to the ViewController's view so that when the view is tapped we dismiss the textfield. It is important to not cancel the subsequent clicks on the view.
Swift 2.3
override func viewDidLoad() {
//.....
let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:)))
//this line is important
viewTapGestureRec.cancelsTouchesInView = false
self.view.addGestureRecognizer(viewTapGestureRec)
//.....
}
func handleViewTap(recognizer: UIGestureRecognizer) {
myTextField.resignFirstResponder()
}
I am creating a sample web application on my iphone... In that application the main page is login page....Users enter their user name and password in the textfield (UITextField), it will verified by program.
My problem is I want to move cursor from One uitextfield to another uitextfield using tab key pressed in the keyboard (Like a windows operation).
How can I do this?
You can move the focus to a particular UITextField by calling:
[myTextField becomeFirstResponder]
If you implement the UITextFieldDelegate in your class by declaring the following method you can handle the "Done" key being pressed on the keyboard, which is the iPhone native app equivalent of pressing tab.
/*****************************************************************************/
/* Handle the Done button being pressed on the keyboard for any of our */
/* editable UITextFields. We either pass the keyboard focus to the next */
/* text field, or we hide the keyboard. */
/*****************************************************************************/
- (BOOL)textFieldShouldReturn:(UITextField *)xiTextField
{
if (xiTextField == myAccountNameTextField])
{
NSLog(#"Done pressed whilst in account name field, pass focus");
[myPasswordTextField becomeFirstResponder];
}
else
{
NSLog(#"No next text field, closing keyboard");
[xiTextField resignFirstResponder];
}
}