Skip to content

Instantly share code, notes, and snippets.

@andkon
Last active December 24, 2015 22:29
Show Gist options
  • Save andkon/6873118 to your computer and use it in GitHub Desktop.
Save andkon/6873118 to your computer and use it in GitHub Desktop.
Dismissing iOS keyboard by pressing return or by pressing the screen
// This should be the viewcontroller that the keyboard commmunicates with.
@interface KeyboardDismissalViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *theTextFieldThatOpensTheKeyboardInTheFirstPlace;
- (IBAction)textFieldDoneEditing:(id)sender;
- (IBAction)backgroundTap:(id)sender;
@end
// add this to the implementation file, then go to the nib/storyboard and:
// 1. Open the connections inspector.
// 2. Drag from the text field's Did End On Exit to the File's Owner
// 3. Connect to the textFieldDoneEditing method.
// Now everytime you press return/done key, that'll fire the below method and dismiss the keyboard.
- (IBAction)textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
// Add this to the implementation file, then go to the nib/storyboard and:
// 1. Select the view that the text field you're editing belongs to.
// 2. Open the identity inspector, and change the view's custom class from UIView to UIControl.
// 3. Open the connections inspector, and drag from Touch Down to the File's Owner.
// 4. Connect to the backgroundTap: method.
// Now everytime you click on a part of the view that isn't an active control, the keyboard will retract.
- (IBAction)backgroundTap:(id)sender
{
[self.theTextFieldThatOpensTheKeyboardInTheFirstPlace resignFirstResponder];
// add any other things that might open up a keyboard!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment