Reputation: 55
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
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
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
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