gpt4 book ai didi

swift - 更改 Controller Swift 时自动关闭键盘

转载 作者:行者123 更新时间:2023-11-28 06:19:19 24 4
gpt4 key购买 nike

在这种情况下,当我在完成编辑后点击所有地方时,我可以关闭键盘。但是,如果我不点击所有地方,我的键盘就会卡住并且无法自动隐藏。示例:当我完成编辑文本字段时,我没有点击任何地方关闭键盘,但我点击了下一个按钮,键盘仍然显示在下一页中。问题:当我瞄准另一个 Controller 时如何自动关闭键盘。

下面的代码是关闭键盘的正常点击。

let dismiss: UITapGestureRecognizer =  UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
mainView.addGestureRecognizer(dismiss)
---------------------------
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}

额外的

这是我获取另一个 Controller 的代码

//Implement UITextFieldDelegate
extension LoginViewController: UITextFieldDelegate{

func textFieldDidBeginEditing(_ textField: UITextField) {
self.hideKeyboardWhenTappedAround()
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "EnterMpinViewController") as! EnterMpinViewController
secondViewController.pinProtocol = self
textField.resignFirstResponder()
self.navigationController?.pushViewController(secondViewController, animated: true)
// self.performSegue(withIdentifier: "entermPINController", sender: self)
}
}

因此,如果我点击 textField,我会跳转到另一个 Controller 以添加 pin。键盘卡在那里。

扩展代码:

//Implement viewWillDisappear
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}

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

最佳答案

您可以创建一个 BaseViewControler,它是 UIViewController 的子类。然后覆盖 viewWillDisappear 方法,并在那里隐藏键盘。并且每个 view controller 都应该是这个 BaseViewController 的子类。

关于swift - 更改 Controller Swift 时自动关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44192824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com