I want to implement an action, when if the user tap somewhere on the screen, then the keyboard should disappear.
I have an app, that look as follow
When I tap on textfield then the keyboard appears, that is good.
Now I want, when I tap somewhere on the screen, then the keyboard should disappear.
I implemented a tap gesture recognizer with following property value:
And the tap gesture recognizer I bound with following action in the view controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var numberField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func textFieldDoneEdition(sender: UITextField) {
sender.resignFirstResponder()
}
#IBAction func onTapGestureRecognized(sender: AnyObject) {
nameField.resignFirstResponder()
numberField.resignFirstResponder()
}
}
Tap gesture recognizer is bound to the function.
And it does not work at all, when I tap somewhere on the screen. The keyboard is still there. What am I doing wrong?
Your view should have the Gesture associated.
Your Gesture should have Sent actions
This should be enough to work.
If for some mystical reason, none of this works, you have an alternative for dismiss keyboard.
func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
Related
I have a UIViewController and I have embedded a Search Bar and a Collection View. When I press on the searchbar, the keyboard appears. I would like to hide this keyboard if the user decides to change his mind by tapping any where on the screen but the search bar. I have tried the following without success:
Adding a Tap Gesture Recognizer
using 'self.mySearchBar.endEditing(true)'
class CollectionViewFolder: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout, UISearchBarDelegate{
/*** OUTLETS ***/
#IBOutlet weak var mySearchBar: UISearchBar!
// 1. I have tried adding a Tap Gesture Recognizer
// TAP ON SCREEN LISTENER
#IBAction func tapOnScreen(_ sender: UITapGestureRecognizer) {
print("tap tap ...")
self.mySearchBar.resignFirstResponder()
}
// 2. Added the following to the viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.mySearchBar.endEditing(true)
}
}
You can use this extension.
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)
}
}
Usage. In your viewController:
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
}
I was trying to create a function in order to put keyboard away by clicking outside of the keyboard or return key within the keyboard, but unfortunately it only worked when I clicked outside of the keyboard, it doesn't work to press the return key in the keyboard.
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet var numberEnter: UITextField!
#IBAction func findButton(sender: AnyObject) {
resultLabel.text = numberEnter.text
}
#IBOutlet var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField:UITextField) -> Bool{
textField.resignFirstResponder()
return true
}
}
If you haven't set the delegate for your text field you will need to do that. You can set the delegate in Interface Builder or in code. See this StackOverflow answer for an example: Text Field Should Return, is this correct for ios7?
I have a screen with a textField and a textView.
I want the textField keyboard to be dismissed on the press of the return key or if a user taps on a blank area of the screen.
Tutorials have shown me to do the following:
#IBOutlet weak var DescriptionContent: UITextView!
#IBOutlet weak var TitleContent: UITextField!
func textFieldShouldReturn(TitleContent: UITextField) -> Bool {
TitleContent.resignFirstResponder()
return false
}
On the storyboard I have clicked on the textField and ctrl dragged a delegate to the yellow icon above my view controller containing the textField.
This did not work.
I have seen on stack overflow to also try:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
TitleContent.resignFirstResponder()
}
super.touchesBegan(touches , withEvent:event)
}
And that didn't work and then I saw to try the following inside the view controllers viewdidload method:
let tapper = UITapGestureRecognizer(target: self.view, action:Selector("endEditing:"))
tapper.cancelsTouchesInView = false
self.view.addGestureRecognizer(tapper);
And that did not work either. The first line of my controller is the following:
class PostController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, UITextFieldDelegate, UITextViewDelegate { ...
And inside my viewDidLoad I have the following:
DescriptionContent.delegate = self
TitleContent.delegate = self
Ultimately I want the user to be able to dismiss the keyboard by pressing outside the textfield and likewise with my textview.
The way I got this to work was by adding this into the viewDidLoad function
var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
and by creating a method called DismissKeyboard which just calls
view.endEditing(true)
This makes it such that if you click anywhere on the screen, that is not the text fields it will close the first responder.
In the textFieldShouldReturn function it should be returning true, if its returning false, it won't cause the first responder to close.
Hope I helped a bit...
I am providing a couple of options that you may want for later.
First how move to new view controller.
#IBOutlet var passCodeText: UITextField! // Make sure you have have this
func textFieldShouldReturn(textField: UITextField) -> Bool {
passCodeText.resignFirstResponder()
self.performSegueWithIdentifier("tableVC", sender: self)
return true
}
To love your main issue.
UITextFieldDelegate // make sure to add this to your class line
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true);
}
I want to dismiss the keyboard interactively, but my code is not working. I don't know why.
When I try the keyboard dismiss mode onDrag it is working fine and there is no need of any more code for that.
Here is my code :
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate{
#IBOutlet weak var txtUserName: UITextField!
#IBOutlet weak var txtPassword: UITextField!
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = false;
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive
// Do any additional setup after loading the view.
}
#IBAction func LoginTapped(sender: AnyObject)
{
//here my code which is running
}
func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive
}
}
Here are screenshots of the simulator
Please take a look and if possible let me know where the error is.
Use this code. This will end editing when you tap anywhere on the screen.
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
}
//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)
}
Hope that helps.
I had the same problem and i finally solved it !
For me the Julian's solution didn't worked so i had to do it as it is :
Set a TapGestureRecognizer in your Storyboard and then an Outlet in your ViewController
#IBOutlet var tapGesture: UITapGestureRecognizer!
Then set an IBAction in your ViewController
#IBAction func DismissKeyboard(sender: UITapGestureRecognizer)
{
self.view.endEditing(true)
}
add these lines to your viewDidLoad method
override func viewDidLoad()
{
super.viewDidLoad()
self.view.addGestureRecognizer(tapGesture)
}
and its should work
Hope that will help !
The below code will work on all the components in the UIView for all the UITextField
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UIView * txt in self.view.subviews){
if ([txt isKindOfClass:[UITextField class]] && [txt isFirstResponder]) {
[txt resignFirstResponder];
}
}
}
I have the following code to hide my keyboard when the user taps the view, but touchesBegan is not firing at all:
class LoginViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var emailAddress: UITextField
#IBOutlet var password: UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Delegate fields
self.emailAddress.delegate = self
self.password.delegate = self
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
self.emailAddress.resignFirstResponder()
self.password.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField!) -> Bool{
self.emailAddress.resignFirstResponder()
self.password.resignFirstResponder()
return true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This view controller is inside of a navigation controller, so not sure if it has something to do with the responder chain
Your code works just fine for me. (Though, typically I would use self.view.endEditing(YES) rather than resignFirstResponder on each text field.)
Most likely the view that you're tapping on is somehow preventing the event from being sent up the responder chain. It could be userInteractionEnabled, an alpha of 0, an override of touchesBegan which doesn't send the events up the responder chain, a gesture recognizer which is eating the touch events, etc. If you make a minimal test case which shows this problem, it'll probably become obvious which of these it is.