dismissing keyboard on return key and also on press outside textfield/text view

358 views Asked by At

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.

2

There are 2 answers

0
MwcsMac On

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);
}
0
repo On

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...