Owen S
Owen S

Reputation: 55

Swift - Text Field Keyboard Return Key Not Working?

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...

Upvotes: 2

Views: 8941

Answers (3)

Julien Ambos
Julien Ambos

Reputation: 2098

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;
}

Upvotes: 1

Marcy
Marcy

Reputation: 6029

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.

Upvotes: 1

Joe Benton
Joe Benton

Reputation: 3753

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
}

Upvotes: 7

Related Questions