0
votes

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
enter image description here

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: enter image description here enter image description here

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. enter image description here And it does not work at all, when I tap somewhere on the screen. The keyboard is still there. What am I doing wrong?

1
did you drag the touch gesture recognizer onto the view ? and is the function actually called ?the_critic
I updated my post, consider the last picture. I set the break point in the function, it does not stop, when tap somewhere on the screen.softshipper
First of all the breakpoints will never be hit because they are not active (in order for them to be active they need to be blue (not faded)). Click them once again to make them blue.the_critic
Can you make a screenshot of the connections inspector (the arrow to the very right in your utilities panel) with your tap gesture recognizer selected ?the_critic

1 Answers

0
votes

Your view should have the Gesture associated.

enter image description here

Your Gesture should have Sent actions

enter image description here

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)