how to hide keyboard immediately after tapping on a text field?

1.3k Views Asked by At

I have a custom textfield. It opens a pop-up using UITableViewController, when user taps on it.

I wanted to prevent keyboard to pop-up for my text field, looks like it is not possible.

So I tried the following code which works in simulator, but it does not work for an actual iPhone!!!

    @IBAction func provincePressed(_ sender: Any) {
         (sender as AnyObject).resignFirstResponder()
         self.view.endEditing(true)

What is wrong? and how can I make it work for an actual iPhone? or possibly prevent keyboard to show up at all!

5

There are 5 best solutions below

0
Stefo On BEST ANSWER

Try to return false in the textFieldShouldBeginEditing method

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
  return false
}
2
SafoineMoncefAmine On

Swift 4

You can just call textField.resignFirstResponder() inside textFieldDidBeginEditing method like this :

-(void)textFieldDidBeginEditing:(UITextField *)textField {     
    if (textField.tag == 1) {
        //this is textfield 2, so call your method here
       textField.resignFirstResponder()
    }
}

You should give the wanted textfield a tag. If you want the same behavior for all textfields in your ViewContriler then that part is not needed.

Also, don't forget to extend your ViewController from UITextFieldDelegate and delegate the textField to your ViewController .

textField.delegate = self

1
matt On

Set the text field’s isEnabled to false beforehand.

0
Harjot Singh On

This is according to the SafoineMoncefAmine Answer.

-(void)textFieldDidBeginEditing:(UITextField *)textField {     
    if (textField == yourTextfield) {// No need tag Use QA Manager to handle the textfield

       textField.resignFirstResponder()
       // Open your menu here, add view, show the menu here.

    }
}

In addition to this answer,

extension MyViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if textField == YourTextField{
        return false
        }
        else{
        return true
        }
    }
}
0
SafoineMoncefAmine On

You can just disable user interaction from UITextField , and cover it with UIView and add uigesturerecognizer to that view to trigger your event .