syedfa
syedfa

Reputation: 2809

Need to dismiss keyboard which appears, when user taps on certain areas of UITableView only

I have a project where I have a UITableView with three different cells, and two sections: section 0 with one cell that contains a UILabel, and section 1 which has two cells, each containing a UITextField. When the user selects the UITextField from either of the cells in the second section, the keyboard appears. This is fine. However, what I would like to do is dismiss the keyboard when the user presses either the cell in section 0 (which also takes the user to another screen), presses the footerView of the UITableView, or outside of the UITableView altogether. My problem right now is that I'm able to dismiss the keyboard, but the first cell does not take the user to the next screen as desired. Here is my code:

    func hideKeyboard() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(MyViewController.dismissKeyboard))

        view.addGestureRecognizer(tap)
    }

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

This method is called from viewDidLoad() as, self.hideKeyboard(). I realize that in my code, I assign the tapGesture to the parent view which disables the tap gesture on the UITableView, but I'm wondering how do I get around this problem to achieve the desired solution I mentioned above?

Upvotes: 0

Views: 48

Answers (1)

Connor Neville
Connor Neville

Reputation: 7361

So you want to dismiss the keyboard based on taps in 3 distinct areas.

  1. Either cell in section 0: subclass UITableViewCell and create your custom cell (if you haven't already). Then, add a UITapGestureRecognizer to the contentView of your custom cell to dismiss the keyboard.
  2. The footer view of the tableView: again, add a tap gesture recognizer to this custom footer view.
  3. Outside of the UITableView altogether: if you truly mean any area that isn't in the UITableView, then create a UIView, add it to your view controller and use view.sendSubviewToBack to send this custom view behind the table view. Then, again, add a tap gesture recognizer to dismiss the keyboard.

Upvotes: 0

Related Questions