Dismiss keyboard through return key with swift
Asked Answered
E

2

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.

Exemption answered 28/7, 2015 at 23:13 Comment(3)
Have you set the delegate of your UITextField?Minni
You aren't overriding the textField... Function. I'm betting that's your problem.Reverie
Yes. That was what I was doing wrong. Thanks everyoneExemption
L
3

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

    @IBOutlet var text: UITextField! {
      didSet {
       text.delegate = self
      }
}
Lavonia answered 29/7, 2015 at 0:37 Comment(0)
V
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
}
Vatic answered 26/9, 2016 at 14:11 Comment(1)
That is what I had. It only works if you add the delegate to the text field.Exemption

© 2022 - 2024 — McMap. All rights reserved.