How to resign keyboard automatically

218 views Asked by At

I'm using IQKeyboardManager. In my UI, I have a textview and below that, a textfield. Now when I tap on thetextview, the keyboard comes up.

And when I tap on the textfield that is below the textview, I bring up a datepicker. But the keyboard that came up when I tapped on the textview still remains there since I didn't press the Done button on the keyboard.

If I tap on my textfield, how can I automatically dismiss the keyboard that came up while tapping on the textview without requiring to press the Done button..?

I tried these but it didn't work...

func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        print("called")
        myTextView.resignFirstResponder()
        return false
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("called")
    }
    
2

There are 2 answers

0
NaveedUlHassan5 On BEST ANSWER
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    if textField == yourTextFieldName {
        //You need to Resign both responders here.
        yourTextView.resignFirstResponder()
        yourTextFieldName.resignFirstResponder()
        //show your date picker
        return false
    } else {
        return true
    }
}

Difference between the two methods.

A "shouldBegin" something allows you to say NO on the return value to prohibit the action.

A "didBegin" something says it has just started to happen and you need to take whatever actions you need to do at that point in time.

0
Roma Kavinskyi On

make sure that you assigned textField.delegate = self

Then, if you want to dismiss the keyboard at the moment you tap on the textfield just correct you textFieldDidBeginEditing method:

func textFieldDidBeginEditing(_ textField: UITextField) {
    myTextView.resignFirstResponder()
    textField.resignFirstResponder()
}