swift 如何关闭数字键盘后,点击文本字段外?

bihw5rsg  于 2023-09-30  发布在  Swift
关注(0)|答案(6)|浏览(106)

在键盘外敲击时,如何将键盘从下一个字段中删除?我试过resignFirstResponder(),它只在输入一个数字后退出。我也试过textField.inputView = UIView.frame(frame: CGRectZero)。我看过很多Objective-C版本,但我需要Swift版本,因为我没有Objective-C编程经验。

ubbxdtey

ubbxdtey1#

向视图添加点击手势识别器的最佳方法是调用resignFirstResponder()或self.view.endEditing(true)。我更喜欢endEditing(),因为resignFirstResponder必须为每个文本字段单独完成,而不像endEditing那样为视图本身完成。
在viewDidLoad中,编写以下代码:

let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: "didTapView")
self.view.addGestureRecognizer(tapRecognizer)

现在编写didTapView方法来关闭键盘:

func didTapView(){
  self.view.endEditing(true)
}

现在,当您在控制器的主视图上点击键盘外部时,它将调用didTapView方法并关闭键盘。

Swift 3.x

viewDidLoad中的代码应为:

let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(ViewController.didTapView))
self.view.addGestureRecognizer(tapRecognizer)

其中ViewController应该是视图控制器的名称。
谢谢

qaxu7uf2

qaxu7uf22#

Swift 3已测试并运行

// dismiss keyboard on touch outside textfield
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for txt in self.view.subviews {
            if txt.isKind(of: UITextField.self) && txt.isFirstResponder {
                txt.resignFirstResponder()
            }
        }
    }

享受
Swift 2.3已测试并运行

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for txt in self.view.subviews {
            if txt.isKindOfClass(UITextField.self) && txt.isFirstResponder() {
                txt.resignFirstResponder()
            }
        }
    }

享受

11dmarpk

11dmarpk3#

您也可以使用此方法在按“Return”时关闭键盘

func textFieldShouldReturn(textField: UITextField!) -> Bool {
        self.view.endEditing(true);
        return false;
}

确保设置您的代理

iecba09b

iecba09b4#

如果您不想定义额外的方法,有一个稍微简单的方法也可以工作

let tapRecognizer = UITapGestureRecognizer(target: self, action: "endEditing:")
view.addGestureRecognizer(tapRecognizer)
ndasle7k

ndasle7k5#

我在一个网站上找到了这段代码,它对我来说很好用!

//FUNCTION TO DISMISS THE KEYBOARD
 func initializeHideKeyboard(){
 //Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
 let tap: UITapGestureRecognizer = UITapGestureRecognizer(
 target: self,
 action: #selector(dismissMyKeyboard))
 //Add this tap gesture recognizer to the parent view
 view.addGestureRecognizer(tap)
 }

 @objc func dismissMyKeyboard(){
 //endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
 //In short- Dismiss the active keyboard.
 view.endEditing(true)
 }

然后在按钮动作或类似动作中调用此函数:

dismissMyKeyboard()
pgx2nnw8

pgx2nnw86#

SWIFT 5

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    
    if textField.isFirstResponder {
        textField.resignFirstResponder()
    }
}

相关问题