Member-only story

Dismiss a keyboard with tap on view iOS

Mr.Javed Multani
1 min readOct 3, 2020

--

If you want to hide a keyboard by tap outside of it, it’s possible to use this hacky trick (works only with Objective-C):

- (void)viewDidLoad {
[super viewDidLoad];// dismiss keyboard when tap outside a text fieldUITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self.view action:@selector(endEditing:)];[tapGestureRecognizer setCancelsTouchesInView:NO];[self.view addGestureRecognizer:tapGestureRecognizer];
}

for Swift there will be a bit more code:

override func viewDidLoad() {
super.viewDidLoad()// dismiss keyboard when tap outside a text fieldlet tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourVCName.dismissKeyboard))view.addGestureRecognizer(tapGestureRecognizer)}//Calls this function when the tap is recognized.func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)}

Another Swift 3/iOS 10 example

class vc: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.txtSomeField.delegate = self
}}extension vc: UITextFieldDelegate {
//Hide the keyboard for any text field when the UI is touched outside of the keyboard.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{self.view.endEditing(true) //Hide the keyboard
}}

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet