DeyaEldeen DeyaEldeen - 4 months ago 10
iOS Question

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

I know how to dismiss a keyboard, I use this extension:

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

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


And add
hideKeyboardWhenTappedAround
in
viewDidLoad


But my problem now is I added a
UITextField
to a navigation bar, and this extension no longer works!

This is how I added the
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


How to dismiss a keyboard brought from a
UITextField
that lurks in a navigation bar?

enter image description here

Answer

Make a reference to this text field, like:

var navigationBarField : UITextField?

Then initialize it:

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

And when you want to remove keyboard call:

navigationBarField?.resignFirstResponder()