-2

I have presented a screen using navigation controller and in that screen I have a search bar , which I have made as first responder in viewWillAppear() . The problem is that I want to hide keyboard when done button is clicked or cancel in searchBar is clicked. But on doing the same with both resignFirstResponder() and searchBar.endEditing(true) , it also hides UISearchBar. I want to show UISearchBar when the state is not in edit also .

Basically what I have done is I have made my UISearchBar my first responder as such :

override func viewWillAppear(_ animated: Bool) {
    searchBar.becomeFirstResponder()
}

then when user clicks search I have made :

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    // Remove focus from the search bar.
}

Same is the case with cancel button . But in my case instead of just dismissing the keyboard , this also hides UISearchbar() after calling the above function.

SwiftNinja95
  • 157
  • 2
  • 16

1 Answers1

0

Use NotificationCenter addObserver to get an event of keyboard show and keyboard Hide

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// MARK: - Keyboard Hide/Show Functions
@objc func keyboardWillShowNotification(notification: Notification) {
    print("Keyboaed Show")
}

@objc func keyboardWillHideNotification(notification: Notification) {
    print("Keyboaed Hide")
}

Note:- Don't forget to remove the observer when UIviewContoller will disappear.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
AtulParmar
  • 4,358
  • 1
  • 24
  • 45