Chris
Chris

Reputation: 147

Dismiss keyboard for textfield in uitableviewcell in tableviewcontroller - Swift

I have a textfield and textview in my custom tableviewcell.

I have 4 different prototype cell with 4 different class created. there is a textfield in 1 prototype cell and a textview in the other.

I am not sure how I can do it and I dont understand the obj-c answers out there.

I've tried

override func viewDidLoad() {
    super.viewDidLoad()

    let tap: UIGestureRecognizer = UIGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
    view.addGestureRecognizer(tap) }

and

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

I wanted to try

UITextFieldDelegate and touchesbegan and textfieldshouldreturn method, but there are no textfields to call in my tableviewcontroller.

Upvotes: 0

Views: 1928

Answers (3)

Vivek Patel
Vivek Patel

Reputation: 170

You can use cancelsTouchesInView for dismiss keyboard .

override func viewDidLoad() {
 super.viewDidLoad()

let tap = UITapGestureRecognizer(target: self, action: 
    #selector(UIInputViewController.dismissKeyboard))

tap.cancelsTouchesInView = false 
view.addGestureRecognizer(tap) 
}

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

Upvotes: 0

ronix
ronix

Reputation: 213

I had same problem, you can solve this with IQKeyboardManager, you don't need to complicate things with the custom cell classes, just install it on your project, when you're all set with installation, in the appDelegate inside the didFinishLaunchingWithOptions method, add this line of code:

IQKeyboardManager.shared.shouldResignOnTouchOutside = true

Get IQKeyboardManager from here.

Upvotes: 0

rmickeyd
rmickeyd

Reputation: 1551

Go to attributes inspector in storyboard and click tableView and set keyboard to dismiss interactively.

Or

Set textField delegate and implement

override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self
 }

func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return false to ignore.
{
    textField.resignFirstResponder()
    return true
}

Upvotes: 1

Related Questions