如何关闭导航栏中文本字段调用的键盘?

How to dismiss a keyboard called by a textfield in the navigation bar?

我知道如何关闭键盘,我使用这个扩展:

extension UIViewController
{
    func hideKeyboardWhenTappedAround()
    {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        view.addGestureRecognizer(tap)
    }
    
    func dismissKeyboard()
    {
        view.endEditing(true)
    }
}

并在 viewDidLoad

中调用了 hideKeyboardWhenTappedAround

但我现在的问题是我将 UITextField 添加到 navigationBar,此扩展程序不再有效!

这就是我添加 UITextField:

的方式
    let textField = UITextField(frame: CGRectMake(0,0,textfieldW,0.8*ram.navigationBarHeight) )
    textField.borderStyle = UITextBorderStyle.RoundedRect
    textField.center.y = centerView.center.y
    centerView.addSubview(textField)
    self.navigationItem.titleView = centerView

如何关闭潜伏在导航栏中的 UITextField 带来的键盘?

引用此文本字段,例如:

var navigationBarField : UITextField?

然后初始化它:

navigationBarField = UITextField(frame: CGRectMake(0,0,textfieldW,0.8*ram.navigationBarHeight) )
textField.borderStyle = UITextBorderStyle.RoundedRect
textField.center.y = centerView.center.y
centerView.addSubview(navigationBarField)
self.navigationItem.titleView = centerView

当你想删除键盘调用时:

navigationBarField?.resignFirstResponder()

你只需要调用 navigationController'sendEditing 方法而不是声明实例 view 也像这样

func dismissKeyboard()
{   
    navigationController?.view.endEditing(true)
    view.endEditing(true)
}