How to manage the keyboard for a UITextField

Share the joy
  •  
  •  
  •  
  •  

When you are dealing with UITextFields one thing you need to handle is the showing and hiding of the keyboard. To show the keyboard all you need to do is make your text field the first responder like this:

[self.myTextField becomeFirstResponder];

If you want the keyboard to be there when your view appears on the screen then add this line of code in the viewDidAppear: rather than the viewWillAppear: method.

If you want to hide the keyboard then all you need to do is resign being the first responder.

[self.myTextField resignFirstResponder];

If you want the keyboard to hide when the user taps outside of the text field the the touchesBegan:withEvent: method is a good place to resign first responder.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.myTextField resignFirstResponder];

}

If you want the keyboard to hide when you press the return or done button of the keyboard then you need to make sure that the view controller is the delegate for your text field and resign first responder in the textFieldShouldReturn: method.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [self.myTextField resignFirstResponder];

    return NO;

}

 

 

 


Share the joy
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

*