简体   繁体   中英

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

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM