iosswiftiqkeyboardmanager

Dismiss keyboard on tapping textfield


I have a textfield which can be edited. Below this textfield, I have another textfield on the tap of which I go to another screen.

When I tap the 1st textfield, the keyboard comes up. But when I tap on the 2nd textfield the keyboard still remains (maybe because it is also a textfield). But I want the keyboard to dismiss the moment I tap the second textfield.

I'm using IQKeyboardManager.

This is what I have..But it's not working...

@IBAction func secondTextfield_Clicked(_ sender: Any) {
        (sender as! UITextField).resignFirstResponder()
         
        self.performSegue(withIdentifier: "mySegue", sender: nil)
}

Solution

  • First you need to set the delegate to the second textfield and implement the textFieldShouldBeginEditing delegate method.

    secondTextField.delegate = self 
    

    In the following delegate method you can check the textfield and return true/false based on your textfield.

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    
       view.endEditing(true) //with will end editing for the view
       if textField == secondTextField {
            self.performSegue(withIdentifier: "mySegue", sender: nil)
            return false
        }
        return true
    }
    

    By returning false for the secondTextField the keyboard will not be opened for the second text field.