Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismissing the keyboard in a UIViewController

Tags:

ios

swift

I'm running this code within a ViewController class that contains UIViewController and SettingsViewDelegate. The View Controller scene contains a text view that has a scroll bar.

 @IBOutlet weak var tvEditor: UITextView!

 override func viewDidLoad() {
    super.viewDidLoad()      

   // Hide keyboard via swipeDownGestureRecognizer.

     let swipeGesture: UISwipeGestureRecognizer = UISwipeGestureRecognizer (target: self, action: "hideKeyboard")

    swipeGesture.cancelsTouchesInView = false

    UISwipeGestureRecognizerDirection.Down

    }

   func hideKeyboard() {
   tvEditor.resignFirstResponder()
}

When I run my project in the iOS Simulator/device, the keyboard does not respond to a downward swipe. I change the orientation of my device to landscape, and then back to portrait, which is when the keyboard disappears. Can someone please tell me where I'm going wrong?

like image 758
A. Noesk Avatar asked Sep 16 '15 19:09

A. Noesk


People also ask

How do you dismiss a keyboard?

Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.

How do you 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 . Causes the view (or one of its embedded text fields) to resign the first responder status.

How do you dismiss a keyboard in Objective C?

In Objective-C:[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil]; This will resign the first responder (and dismiss the keyboard) every time, without you needing to send resignFirstResponder to the proper view. No matter what, this will dismiss the keyboard.


1 Answers

First, Please add swipeGesture to your viewcontroller. And...

func hideKeyboard() {
    self.view.endEditing(true)
}

It'll works fine for your project. Hope it'll help you.

like image 111
Richard Avatar answered Sep 30 '22 16:09

Richard