4

I am a beginner programmer working with Swift. I have been working on a to-do list application. I am trying to dismiss a keyboard through the return key. I have tried the 'self.view.endEditing(true)' and the 'resignFirstResponder()' methods, but neither of them are working. Here is my code: (I am using a tab-application)

class SecondViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var text: UITextField!

@IBAction func addItem(sender: AnyObject) {

    toDoList.append(text.text)

    text.text = ""

    self.view.endEditing(true)
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    self.view.endEditing(true) // This works fine here

}

func textFieldShouldReturn(textField: UITextField) -> Bool {

    self.view.endEditing(true) // This is not working...
    return true

}
}

At the last function, I have also tried using the following:

func textFieldShouldReturn(textField: UITextField) -> Bool {

    text.resignFirstResponder() // This is not working...
    return true

}

But for some reason, neither one is working as I want it to. When I use it in the 'touchesBegan' method, it works fine. Could you please show me what error I am making in my code? Thanks.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61

2 Answers2

3

Try setting the delegate. Add a didSet to the text outlet. Like this.

    @IBOutlet var text: UITextField! {
      didSet {
       text.delegate = self
      }
}
Epic Defeater
  • 2,107
  • 17
  • 20
2

The resignFirstResponder() method is the correct one. And by using textField.resignFirstResponder() inside of the textFieldShouldReturn() method it works with every text field.

so thats it:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}
RamenChef
  • 5,557
  • 11
  • 31
  • 43