2

I am fairly new to swift and was working on a project where I included a text field. When I tested out the app, I noticed that the keyboard return key doesn't work and I am unable to exit the keyboard. Is there a reason why it does this? Can the return key's functionality be implemented through swift?

Also, there is another app I was recently working on that I switched the keyboard of a text field to number pad, and I realize there is no return key on the number pad, so again, I can't seem to figure out how to exit it. How could I fix this?

Sorry, I am pretty new to apple devices as well...

caseynolan
  • 1,236
  • 1
  • 9
  • 11
Owen S
  • 55
  • 1
  • 6

3 Answers3

7

You want to implement UITextFieldDelegate in your view controller:

class ViewController: UIViewController,UITextFieldDelegate //set delegate to class

and then in viewDidLoad set the textField delegate to self.

override func viewDidLoad() {
   super.viewDidLoad()
   textField.delegate = self
}

You can then add this method which runs when the return key is pressed, and resignFirstResponder which closes the keyboard:

func textFieldShouldReturn(textField: UITextField!) -> Bool {   //delegate method
  textField.resignFirstResponder()
  return true
}
Joe Benton
  • 3,703
  • 1
  • 21
  • 17
1

For other newbies like myself, if you still don't have a keyboard on the simulator after following Joe's excellent instructions then go to the Simulator's menu and select Hardware/Keyboard/Toggle Software Keyboard.

Marcy
  • 4,611
  • 2
  • 34
  • 52
1

Please note that in Swift 4 it seems that the first parameter name of textFieldShouldReturn has to be omitted with an underscore. Elsewise Swift does not call the function:

func textFieldShouldReturn(_ textField: UITextField!) -> Bool { // use "_"
    return true;
}
Julien Ambos
  • 2,010
  • 16
  • 29
  • Still can't get this to work. I am using the right delegate, have assigned the delegate in `viewDidLoad` - not being fired at all. – JCutting8 Mar 08 '20 at 22:23