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

时间:2016-07-25 08:31:27

标签: ios swift uinavigationbar

我知道如何解雇键盘,我使用这个扩展名:

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

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

hideKeyboardWhenTappedAround

中调用viewDidLoad

但我现在的问题是我向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带来的键盘?

enter image description here

2 个答案:

答案 0 :(得分:1)

引用此文本字段,例如:

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

答案 1 :(得分:1)

而不是声明实例,您只需要调用endEditing navigationController's的{​​{1}}方法,就像这样

view