I’ve updated my hobby project to take keyboard input. This ought to be pretty simple, but I came across a few snags that stopped the user experience being as smooth as should be.
Simulator only presents the pop-up keyboard once
This has been bothering me for a while, I resorted to switching to a different simulator profile (e.g. iPhone 4s / iPhone 5). It turns out that, by typing into the laptop keyboard instead of tapping the UI keyboard, the switch to hardware keyboard was semi-permanent. As per this StackOverflow page, you can restore the keyboard by in the Similar by Hardware -> Keyboard -> Toggle Software Keyboard (or ⌘K).
How to change the pop-up keyboard to ‘Done’
By default, the pop-up keyboard shows the enter/return key as “Return”. For some instances, you want to change that – this is as simple as changing the “Return Key” property on the text field in the story board:
How to dismiss keyboard when user presses return key
By default, the software keyboard does not disappear when you tap return (either on the hardware keyboard or on the software keyboard). There are several steps to achieve this, which are well discussed on StackOverflow. There are a couple of implementations choices for textFieldShouldReturn, this one worked for me:
// UITextFieldDelegate implementation func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false }
coupled with the change below for leaving the text field.
How to dismiss keyboard when user leaves the text field
Another obvious feature I wanted is to dismiss the keyboard if the user taps elsewhere in the App. The key here is to tell the view to recognise a tap (that is, UITapGestureRecognizer). See ‘Close iOS keyboard by touching anywhere’ on StackOverflow discussion.