AlexLeo
AlexLeo

Reputation: 89

How to hide keyboard in TableViewController when tap on other cell?

I have TableViewController with UITextFields as cells and cells without TextField.
I would like to hide the keyboard when I tapped on another cell without TextField

Upvotes: 2

Views: 943

Answers (4)

Nathaniel Gonzales
Nathaniel Gonzales

Reputation: 62

try using "IQKeyboardManagerSwift", it has all the keyboard controls that you will need in the future.

Upvotes: 2

A.Munzer
A.Munzer

Reputation: 1990

You have two ways to handle it, first you can hide keyboard when the user tapped on cells without TextField, by table view delegate, but you should ignore the rows that had textfiled

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    view.endEditing(true)
}

Or you can add UITapGestureRecognizer to the cells that dose not had text field

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

    view.addGestureRecognizer(tap)
}

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

Upvotes: 1

Anupam Mishra
Anupam Mishra

Reputation: 3588

This could be helpful-

extension YourViewController: UITableViewDelegate {

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            self.view.endEditing(true)
        }
    }

Upvotes: 1

vdmzz
vdmzz

Reputation: 261

In your UITableViewDelegate implementation:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    view.endEditing(true)
}

Upvotes: 2

Related Questions