Hide keyboard plus return key?

214 views Asked by At

I have a view with a textfield at the top, a textview under it and two buttons below the textview.

The keyboard is configured with a "Done" button. Once the user has typed in their info, they click the save button, which is below the textview. First they click Done to hide the keyboard (and reveal the save button) then click the save button.

I need to allow carriage returns in the textview but "Return" is already taken up by Done.

How is it usually handled when you need a Return key and ability to also hide the keyboard?

2

There are 2 answers

0
clearlight On BEST ANSWER

If you're using a UINavigationBar or have other buttons or fields, activating any of those UIControls could be detected and used to dismiss the keyboard via resignFirstResponder(). In fact Save/Cancel/Done are UIBarButtonItems and are a standard mechanism for completing things and changing state, and create a framework for accomplishing what you want. If you don't take that approach then you have to get creative with how you do it, and also make it clear to the user what needs to be done.

In Interface Builder you can change the type of your main view from UIView to UIControl and then use addTarget() to detect touch events as a 'touch outside' area and use those actions to resign first responder as well. But you might want to consider a UINavigationBar or some other button bar or tab interface to make state transitions.

Also review iOS Human Interface Guidelines document. It's a great document for understanding how iOS is designed to handle common situations like what you are dealing with, and it can get you out of design ruts. It's well written and worth re-visiting periodically.

2
Shades On

Drag a button into your view, delete the text, and resize it to take up the entire view. In the document outline, select the new button and drag it to the top of the list of elements. This puts it in the background so it is not hiding the elements of your view.

Add this code to your ViewController:

@IBAction func hideKeyboard(sender: AnyObject) {
    self.textField.resignFirstResponder()
}

Link the button to this action and you're all set.