Hide the keyboard with return key for an UITextField in a tableviewcell

Viewed 38

I have a view with a embedded tableview in it in which i have a UITextField and I want to hide the keyboard when I press the done button

my Storyboard

My Code is the following:

My tableViewController:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "playerCell", for: indexPath) as? PlayerNameTableViewCell else {fatalError("Wrong type of cell")}

        // Configure the cell...
        cell.playerName.delegate = self

        return cell
}

My cell:

class PlayerNameTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var playerName: UITextField!

    @IBAction func enterButton(_ sender: UITextField) {
        sender.resignFirstResponder()

    }

}

But nothing happens when I press the done button.

1 Answers

Try adding the following function to the class that implements the UITextFieldDelegate:

func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    textField.resignFirstResponder()

    return true
}
Related