Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Dismiss UITextView Keyboard

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

like image 687
Azabella Avatar asked Feb 02 '15 14:02

Azabella


People also ask

How do I dismiss a keyboard in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing .

How do you dismiss keyboard when tapping outside textfield?

To make the keyboard go away itself, we need to remove “focus” from all of our text fields (if your app has more than one text field) by calling the unfocus() method: FocusManager. instance.

How do I enable the keyboard in Swift?

To enable SwiftKey and make it your default keyboard on stock Android, head to settings, select Language & input, and choose SwiftKey from the list of options.


2 Answers

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
}
like image 116
rakeshbs Avatar answered Sep 20 '22 02:09

rakeshbs


swift 3

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}
like image 36
Hardik Thakkar Avatar answered Sep 23 '22 02:09

Hardik Thakkar