Dismiss keyboard on tapping textfield

151 views Asked by At

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

There are 2 answers

0
Mahendra On BEST ANSWER

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.

0
Mustafa GT On

First of all why are you using textfield to go to anther page? why don't you just use button instead Second thing, if you want you can do this:

override func viewDidLoad() {
     super.viewDidLoad()
     ...
     secondTF.delegate = self
     ...
}

And call this function anywhere in your code:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
   view.endEditing(true) 
   if textField == secondTF {
        // Navigate to the second VC with using storyBoard or navigationController
        return false
    }
    return true
}