0

I'm having some trouble running a function after the return key is pressed on keyboard. I'm trying to get the keyboard to be dismissed when the return key is pressed but I found that the function is not being run at all. If anybody could please take a look I'd greatly appreciate it. Thanks!

class ViewController: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        addWelcomeLabel()
        print("view running")
        self.nameRequestField.delegate = self
    }

    let nameRequestField = UITextField(frame: CGRect(x: 0, y: 0, width: 330, height: 40))
    func textFieldShouldReturn(textField: UITextField) -> Bool {
      //nameRequestField.resignFirstResponder()
        print("hello")
        return true
    }
}
Nayan Dave
  • 1,078
  • 1
  • 8
  • 30
  • 1
    `func textFieldShouldReturn(textField: UITextField) -> Bool {` should be `func textFieldShouldReturn(_ textField: UITextField) -> Bool {` – MadProgrammer Mar 12 '20 at 03:21
  • Does this answer your question? [How to dismiss keyboard for UITextView with return key?](https://stackoverflow.com/questions/703754/how-to-dismiss-keyboard-for-uitextview-with-return-key) – Nayan Dave Mar 12 '20 at 04:59

3 Answers3

1

use This

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    print("hello")
    return true
}
Dilan
  • 2,610
  • 7
  • 23
  • 33
0
func textFieldShouldReturn(_ textField: UITextField) -> Bool{

    return textField.resignFirstResponder()
}
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Igor F. Mar 12 '20 at 06:59
0

You can use this method

func textFieldShouldReturn(textField: UITextField) -> Bool {
        nameRequestField.resignFirstResponder()
        return true
}
Vicky_Vignesh
  • 584
  • 2
  • 14
vivek
  • 1
  • This code snippet does not resolve the question. Additionally, it has no functional difference with the snippet provided by the person asking. Also, please fix the indentation. – Isaaс Weisberg Mar 12 '20 at 07:02