Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MacDeuterium

macrumors newbie
Original poster
Aug 18, 2014
2
0
Canberra, Australia
Hello everybody,

I need to know how to dismiss a keyboard when the user taps a UITextField either by:

1. The user tapping the 'Done' or the 'Return' button in the bottom left hand side of the keyboard, or;
2. The user tapping outside the keyboard field, and the keyboard is dismissed (preferred method)

I'm coding in Xcode 5 for iOS 7 so Objective - C is my preferred language, not Swift. :)

Thanks!

:apple:
 

vubk

macrumors newbie
Aug 19, 2014
5
0
re: iOS App Development - How to Dismiss Keyboard

For question 2, you can try the below code:

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

UITouch *touch = [[event allTouches] anyObject];
if ([_textField isFirstResponder] && [touch view] != _textField) {
[_textField resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}

Change _textField by your name of textField.
 
Last edited:

AxoNeuron

macrumors 65816
Apr 22, 2012
1,251
855
The Left Coast
For the first question, it is somewhat more complicated (but still easy) to make the keyboard go away when the user taps the Done button. First, you have to conform your view controller to the UITextFieldDelegate. Then, you have to use the UITextField delegate method called textFieldShouldReturn:

Code:
#pragma mark UITextFieldDelegate methods
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textField resignFirstResponder];
    return YES;
}

Inside of the viewDidLoad method of the view controller, make sure to set self.textFieldX.delegate = self.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.