Hiding Keyboard iOS

How to dismiss keyboard iOS programmatically when pressing return

The simple way is to connect the delegate of UITextField to self (self.mytestField.delegate = self) and dismiss the keyboard in the method textFieldShouldReturn using [textField resignFirstResponder];

Another way to dismiss the keyboard is the following:

Objective-C

[self.view endEditing:YES];

Swift:

self.view.endEditing(true)

Put [self.view endEditing:YES]; where you would like to dismiss the keyboard (Button event, Touch event, etc.).

Close iOS Keyboard by touching anywhere using Swift


override func viewDidLoad() {
super.viewDidLoad()

//Looks for single or multiple taps.
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false

view.addGestureRecognizer(tap)
}

//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}

Here is another way to do this task if you are going to use this functionality in multiple UIViewControllers:

// Put this piece of code anywhere you like
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
view.endEditing(true)
}
}

Now in every UIViewController, all you have to do is call this function:

override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
}

This function is included as a standard function in my repo which contains a lot of useful Swift Extensions like this one, check it out: https://github.com/goktugyil/EZSwiftExtensions

How do I dismiss the iOS keyboard?


[myTextField resignFirstResponder]

Here, second paragraph in the Showing and Hiding the Keyboard section.

How to hide Keyboard which is in another window? Swift

First, get a reference to host app keyWindow

  func getHostKeyWindow() -> UIWindow? {
if #available(iOS 13, *) {
return windows.first { $0.isKeyWindow }
} else {
return keyWindow
}
}

And then simply make endEditing as true

UIApplication.shared.getHostKeyWindow()?.endEditing(true)

It should close the keyboard in the window for which you have the reference!

Hide keyboard by pressing button


[self.view endEditing:YES]

Paste it in action handler of your controller.
Or for Swift:

self.view.endEditing(true)


Related Topics



Leave a reply



Submit