iosswiftkeyboard-eventsiqkeyboardmanager

How to resign keyboard automatically


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")
    }
    

Solution

  • 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.