2

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!

Hal Mueller
  • 7,019
  • 2
  • 24
  • 42
Netzer
  • 227
  • 1
  • 3
  • 8
  • you can use textfieldshouldReturn delegate method and write in it textfield.resignFirstRsponder and return true – Rajan Maheshwari Dec 22 '15 at 16:51
  • You haven't implemented any methods that would dismiss the keyboard, so of course it's not being called. Have a look at http://stackoverflow.com/questions/5306240/iphone-dismiss-keyboard-when-touching-outside-of-uitextfield – Belle Dec 22 '15 at 16:53
  • @Rajan: Thank you, it works! However, i don't understand the difference to textFieldShouldEndEditing (with resignFirstResponder). Obviously this is what people suggests in a lot of answers around here and should have the same result. – Netzer Dec 23 '15 at 09:34

3 Answers3

6

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.

jcaron
  • 17,302
  • 6
  • 32
  • 46
5

Swift 4.0

tableView.keyboardDismissMode = .onDrag

or

tableView.keyboardDismissMode = .interactive
Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
1

why dont you try textFieldShouldReturn delegate of UITextfield.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;}
Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78