Reputation: 847
I am having trouble dismissing the keyboard of a text view in swift.
I was able to dismiss a textfield with the following
@IBAction func DismissKeyboard(sender: AnyObject)
{
self.resignFirstResponder()
}
But I'm not sure how I go about it with a text view
Upvotes: 8
Views: 10592
Reputation: 981
This is a much better more-intuitive (for your user) solution for dismissing soft keyboard. The problem with the "\n" solution is the user cannot insert line-breaks in the textView-- as hitting the return/done button on the keyboard will dismiss the keyboard before the line break occurs. The method below lets you keep that functionality while teaching the user that just tapping outside text-entry fields is a standard way of dismissing keyboards.
// MARK: - dismiss keyboard when user taps outside of text boxes
override func viewDidLoad() {
super.viewDidLoad()
configureTapGesture()
}
private func configureTapGesture() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(WriteJournalEntryViewController.handleTap))
view.addGestureRecognizer(tapGesture)
}
@objc func handleTap() {
view.endEditing(true)
}
(assumes this code is inside a UIViewController custom subclass named "WriteJournalEntryViewController).
view = your entire view in the UIViewController, so it works for more than just your textView object. endEditing = a method for UIView class, you can read its documentation.
Upvotes: 0
Reputation: 15991
swift 3
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}
Upvotes: 2
Reputation: 24572
You have to set the textview.delegate
to self and use the shouldChangeTextInRange
function to resign on pressing return.
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" // Recognizes enter key in keyboard
{
textView.resignFirstResponder()
return false
}
return true
}
Upvotes: 24
Reputation: 22343
just add the UITextView as an IBOutlet and use the same function:
@IBAction func DismissKeyboard(sender: AnyObject) {
yourtextView.resignFirstResponder()
}
Upvotes: 0