user3483697
user3483697

Reputation: 123

Dismiss keyboard when tapped outside of a textview in a scroll view

The scrollview takes up the whole viewcontroller. A textview is placed in the scrollview. I wish to dismiss the keyboard when the use taps outside of the keyboard.

boostContent is the IBOutlet of the textview.

I've tried the code below and it doesn't work.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.scrollView.endEditing(true)
    boostContent.resignFirstResponder()

}

What's the correct solution?

I've also tried self.view.endEditing(true)

Upvotes: 0

Views: 822

Answers (2)

Senõr Ganso
Senõr Ganso

Reputation: 1734

One way is to add a tap gesture to your view controller and resign the first responder there. The other way, and I think is a better one, is to use a container view. You put it inside you scrollview and then put all your objects, including the textfield, in the container view.

Upvotes: 0

vacawama
vacawama

Reputation: 154523

Add a Tap Gesture Recognizer to the same view holding your text view. Wire it up to this:

@IBAction func tapped(sender: AnyObject) {
    boostContent.resignFirstResponder()
}

I think the issue with what you were trying to do is that your touchesBegan wasn't being called because it is defined on your ViewController and the content view of the scroll view is intercepting the touches.

Upvotes: 3

Related Questions