Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextfield inside UITableViewCells - dismiss keyboard

I have a couple of UITextfields in each table cell. By hitting the "Done" button or touching outside the keyboard, the keyboard should be dismissed.

My problem: the textFieldShouldEndEditing method is only called when I tap another textfield and the keyboard won't be dismissed. I think i've implemented the necessary parts (Delegate and protocol methods).

Does anyone know what I'm missing here....?

Here is the code (the relevant part):

class myVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate  {...

This is the cell setup...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let tcell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "tbCell")

    let textfield: UITextField = UITextField(frame:...

    switch (indexPath.section) {
    case 0: ...
    case 1: 
            textfield.text = section2[indexPath.row]
            tcell.addSubview(textfield)
            textfield.delegate = self
            return tcell

and this the protocol method:

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        print("method is called")
        return true
    }

Thank you!

like image 970
Netzer Avatar asked Dec 06 '25 00:12

Netzer


1 Answers

I am giving this answer in Objective-C because I don't use Swift

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

when you will scroll your tableview, and:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

when you will touch outside textfield.

like image 57
Archit Dhupar Avatar answered Dec 07 '25 14:12

Archit Dhupar