How to dismiss keyboard by tapping on screen - ios

I am looking for a simple solution in swift to add the ability to tap anywhere on screen and dismiss the keyboard. I read a lot of answers on here but they all throw errors for me. The one I have used before is this:
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
This worked with one of my projects but it doesn't seem to work with any others. Whenever I try to add this to other projects I get error Type 'ViewController' has no member 'dismissKeyboard'.

You need to add a method above any reference to it. I put this code at the beginning of my files:
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status and drop into background
view.endEditing(true)
}
And then whenever I need to reference the .dismissKeyboard I use this inside the viewDidLoad():
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))
view.addGestureRecognizer(tap) // Allows dismissal of keyboard on tap anywhere on screen besides the keyboard itself
And make sure to replace 'LoginViewController' with the current View Controller. As per your example, that is just 'ViewController'
If you are looking for a more in depth answer, see this by 7KV7:
https://stackoverflow.com/a/5711504/6312593

You can try this one, its very simple solution, frequently used in swift to dismiss the keyboard.
Just add this function, that's it.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
self.view.endEditing(true)
}

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismiss:"))
view.addGestureRecognizer(tap)
func dismiss(gest : UITapGestureRecognizer){
view.endEditing(true)
}
This is working fine, try it.

Related

iOS 13.0 Touch begin delayed increased compare to ios 12

In my project I have tap gesture with following setup
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(sceneViewTapped(gesture:)))
tapGesture.cancelsTouchesInView = true
tapGesture.delaysTouchesBegan = true
self.view.addGestureRecognizer(tapGesture)
And also has Touch method like override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
I have setup touch gesture with tapGesture.delaysTouchesBegan = true to work both gesture as well as Touch delegate methods
It is working fine till iOS12, But in iOS13 Touch delay has been increased so user must drag his finger and wait until drawing starts because touch method called delayed
Please refer below image , Sometime gesture lost , Delayed on starting of drawing.
If I remove delaysTouchesBegan it is smooth again.
Can anyone can help me to solve this ?
SAMPLE PROJECT
To quick test this stuff download raywenderlich project https://www.raywenderlich.com/5895-uikit-drawing-tutorial-how-to-make-a-simple-drawing-app
Add Following code in ViewController.swlft
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gesture:)))
tapGesture.delaysTouchesBegan = true
self.view.addGestureRecognizer(tapGesture)
}
#objc func viewTapped(gesture:UITapGestureRecognizer) {
print("View Tapped")
}
This was iOS 13.0 bug
After update to the iOS 13.1 Will fix this issue automatically
Hopefully helpful to someone :)

How to remove the dismiss keyboard action on tapping outside MDCTextField

I am trying to use an MDCTextField and a table view together. The MDCTextField filters the table view, then the user should tap a cell and the keyboard should dismiss and the table view should be hidden. The issue is that the keyboard dismisses and the table view is hidden before the table view registers that a cell was tapped. How can I register that a cell was tapped before the MDCTextField registers the tap?
I use this extension you can place in a helpers.swift file but this way you can use on any UIViewController
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
To use it, on viewDidLoad() just add this self.hideKeyboardWhenTappedAround()
EDIT Based on comment
In theory the following code should help, but I haven't got around to test it, I've read that people couldn't get the touchBegan function to trigger but I also don't know any other way to do what you want.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: view)
if let ip = tableView.indexPathForRow(at: position) {
let cell = tableView.cellForRow(at: ip)
print(cell.text)
}
}
}
The theory is the following
First we get the position where the tap occurred then we get the IndexPath for the row witch was taped (if exists) as we have the IndexPath we just get the cell.
In the example I gave you I print the cell text, but you can do any other operation that you want
I hope this is what you want and you can get it to work as I did not got around to test it and seems that some people are getting problems triggering the touchesBegan function

How do you dismiss keyboard in Swift when you touch screen [duplicate]

This question already has answers here:
How to dismiss keyboard when touching anywhere outside UITextField (in swift)?
(19 answers)
Closed 4 years ago.
I have been trying to make the keyboard dismiss when I touch off the keyboard. I found one piece of code that seems to work (kind of), but it only works if I am not touching any other kind of view. By this I mean, I have a scroll view that takes up the majority of the screen. If I tap off the scroll view it will disappear, but if I tap anywhere on the scroll view, nothing happens. This is the code segment I am using. Any help would be much appreciated.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
You can try
let singleTap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
singleTap.numberOfTapsRequired = 1
scrollView.addGestureRecognizer(singleTap)
//
#objc func handleTap(_ recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}

Text dissapearing of Text Field when view.endEditing(true) iOS (Swift 2.0)

my problem is the following, I don't know if is a bug or if I'm doing something wrong. The thing is that I have a view as shown below, and have two text field (the third one was for testing purposes), but I only can see the text if I have the UITextField focused, once I tap anywhere else but the TextFields view.endEditing(true) is executed. and then the text is not gone, but not visible either. There is text in the second and third textField. ¿Any ideas?
UPDATE: Added code for better comprenhension.
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "fondo_nadserv")!)
otroDatoField.delegate = self
datoField.delegate = self
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func DismissKeyboard(){
view.endEditing(true)
}}

Swift - How to dismiss number keyboard after tapping outside of the textfield

How would you dismiss the keyboard from the UITextField when tapping outside of the keyboard. I have tried resignFirstResponder() and it only exits after typing one number. I have also tried textField.inputView = UIView.frame(frame: CGRectZero). I have seen many Obj-C verisons of what I'm asking but I need the Swift equivalent because I have no programming experience in Objective-C
Thank you for your time and patience.
The best way to add a tap gesture recognizer to the view and calling either resignFirstResponder() or self.view.endEditing(true). I prefer endEditing() since resignFirstResponder has to be done for each text field separately unlike endEditing which is done for the view itself.
In viewDidLoad, write the below code:
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: "didTapView")
self.view.addGestureRecognizer(tapRecognizer)
Now write the didTapView method to dismiss the keyboard:
func didTapView(){
self.view.endEditing(true)
}
Now when you tap outside the keyboard on the main view of the controller, it will call the didTapView method and dismiss the keyboard.
Swift 3.x
The code in viewDidLoad should be:
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(ViewController.didTapView))
self.view.addGestureRecognizer(tapRecognizer)
where ViewController should be the name of your view controller.
Thanks
Swift 3 tested and working
// dismiss keyboard on touch outside textfield
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for txt in self.view.subviews {
if txt.isKind(of: UITextField.self) && txt.isFirstResponder {
txt.resignFirstResponder()
}
}
}
Enjoy
Swift 2.3 tested and working
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for txt in self.view.subviews {
if txt.isKindOfClass(UITextField.self) && txt.isFirstResponder() {
txt.resignFirstResponder()
}
}
}
Enjoy
You could also use this method to dismiss the keyboard when pressing 'Return'
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
Make sure to set your delegate
If you don't want to define an extra method, there is a slightly simpler way that will also work
let tapRecognizer = UITapGestureRecognizer(target: self, action: "endEditing:")
view.addGestureRecognizer(tapRecognizer)
I found this code on a site and it works great for me!
//FUNCTION TO DISMISS THE KEYBOARD
func initializeHideKeyboard(){
//Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(dismissMyKeyboard))
//Add this tap gesture recognizer to the parent view
view.addGestureRecognizer(tap)
}
#objc func dismissMyKeyboard(){
//endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
//In short- Dismiss the active keyboard.
view.endEditing(true)
}
Then just call this function in a button action or similar:
dismissMyKeyboard()

Resources