Joan
Joan

Reputation: 1385

Can't dismiss keyboard when editing UITextView and touching anywhere outside of keyboard in table view controller

I have a couple textViews in one cell in a table view controller and I am trying to dismiss the keyboard when you touch anywhere outside the keyboard. I've tried the touches began method but it didn't work. The text views are not transparent and have user interaction enabled.

class RegisterTableViewController: UITableViewController {
    override func viewDidLoad() {
      // set all text views delegate to self
    }

    // dismiss keyboard on touch
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touch")
        super.touchesBegan(touches, with: event)
        view.endEditing(true)
    }
}

extension RegisterTableViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        textView.text = ""
    }
}

I'm new to swift and would appreciate any help!

Upvotes: 0

Views: 364

Answers (2)

Nayan Dave
Nayan Dave

Reputation: 1680

  • Add touchesBegan code in your UITableViewCell file , which will work if you touch outside TextField but inside cell

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
          self.Your_TextField.endEditing(true)
    }
    
  • But it won't work outside cell (In UIVIew of another ViewController) , so add UITapGesture to achieve that

    override func viewDidLoad() {
    super.viewDidLoad()
         let tapgest = UITapGestureRecognizer(target: self, action: #selector(taptoend))
    
         self.Your_Table_View.addGestureRecognizer(tapgest)
    }
    
    @objc func taptoend()
    {
         self.Your_Table_View.endEditing(true)
         print("Key-Board will be dismissed here")
    }
    

Upvotes: 1

Zain
Zain

Reputation: 153

You need to add Tap gesture recognizer inside your cell. Place all you text inputs in a UIView. make outlet of UIView inside cell. and than add this code in your cell.

@IBOutlet weak var myView: UIView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    let tap = UITapGestureRecognizer(target: self, action:    #selector(self.dismissKeyboard))
    self.myView.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
    self.endEditing(true)
}

Upvotes: 1

Related Questions