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

时间:2019-02-24 12:52:23

标签: ios swift keyboard uitextfield resignfirstresponder

我有一个自定义文本字段。当用户点击时,它会使用UITableViewController打开一个弹出窗口。

我想阻止键盘弹出我的文本字段,看来这是不可能的。

所以我尝试了以下在模拟器中可用的代码,但是它不适用于实际的iPhone!

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

怎么了?怎样才能在实际的iPhone上使用它?或完全阻止键盘显示!

5 个答案:

答案 0 :(得分:1)

尝试在textFieldShouldBeginEditing方法中返回false

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

答案 1 :(得分:1)

预先将文本字段的isEnabled设置为false

答案 2 :(得分:0)

快捷键4

您可以像这样在textField.resignFirstResponder()方法内调用textFieldDidBeginEditing

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

您应该给想要的文本字段添加标签。如果您希望 ViewContriler 中的所有文本字段具有相同的行为,则不需要该部分。

此外,不要忘记从UITextFieldDelegate扩展ViewController并将textField委托给ViewController。

textField.delegate = self

答案 3 :(得分:0)

这是根据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.

    }
}

除了这个答案,

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

答案 4 :(得分:0)

您只需从UITextField禁用用户交互,并用UIView覆盖它,然后在该视图中添加uigesturerecognizer即可触发您的事件。

相关问题