Derek Derek - 4 months ago 64
Swift Question

Using UITextView in UITableViewController - tap outside to dismiss keyboard

I'm using a text view inside a table cell. Other cells are associated with segues so I need the following behaviour:


  1. (Default) Tapping on other table rows triggers relevant segue

  2. Tapping inside the text view begins editing and shows the keyboard

  3. If the keyboard is visible, tapping outside the text view dismisses the keyboard but does not follow segues

  4. Once the keyboard has been dismissed, subsequent taps on segues are followed.


Answer

1. Adopt the textView delegate method and

textView.delegate = self

2. Add global property

var tap = UITapGestureRecognizer()

3. Implement the textView delegate methods

func textViewDidBeginEditing(textField: UITextView) { self.tableView.allowsSelection = false tap = UITapGestureRecognizer(target: self, action: #selector(self.Tapped)) self.view.addGestureRecognizer(tap) }

func textViewDidEndEditing(textField: UITextView) { self.tableView.allowsSelection = true self.view.removeGestureRecognizer(tap) }

4. Implement the Tapped()

func Tapped(){ view.endEditing(true) }

Note : This also works for UITextField, replacing View with Field throughout

Comments