Netzer
Netzer

Reputation: 237

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!

Upvotes: 2

Views: 4111

Answers (3)

Abhishek Jain
Abhishek Jain

Reputation: 4737

Swift 4.0

tableView.keyboardDismissMode = .onDrag

or

tableView.keyboardDismissMode = .interactive

Upvotes: 5

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

why dont you try textFieldShouldReturn delegate of UITextfield.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;}

Upvotes: 1

Archit Dhupar
Archit Dhupar

Reputation: 81

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.

Upvotes: 6

Related Questions