简体   繁体   English

如何在点击文本字段后立即隐藏键盘?

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

I have a custom textfield. 我有一个自定义文本字段。 It opens a pop-up using UITableViewController , when user taps on it. 当用户点击它时,它会使用UITableViewController打开一个弹出窗口。

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!!! 所以我尝试了下面的代码,它在模拟器中工作,但它不适用于真正的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? 我怎样才能让它适用于真正的iPhone呢? or possibly prevent keyboard to show up at all! 或者可能阻止键盘出现!

Try to return false in the textFieldShouldBeginEditing method 尝试在textFieldShouldBeginEditing方法中返回false

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

事先将文本字段的isEnabledfalse

Swift 4 斯威夫特4

You can just call textField.resignFirstResponder() inside textFieldDidBeginEditing method like this : 你可以在textFieldDidBeginEditing方法中调用textField.resignFirstResponder()如下所示:

-(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. 如果您希望ViewContriler中的所有文本字段具有相同的行为,则不需要该部分。

Also, don't forget to extend your ViewController from UITextFieldDelegate and delegate the textField to your ViewController . 另外,不要忘记从UITextFieldDelegate扩展ViewController并将textField委托给ViewController。

textField.delegate = self

This is according to the SafoineMoncefAmine Answer. 这是根据SafoineMoncefAmine答案。

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

您可以从UITextField禁用用户交互,并使用UIView覆盖它,并将uigesturerecognizer添加到该视图以触发您的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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