0

When the cancel button of the search bar is tapped I want to resign the keyboard but the current issue is that my function to handle the cancel button is not working.. You can see my code here:

searchBar.rx.cancelButtonClicked
                .asDriver(onErrorJustReturn: ())
                .drive(onNext: { [searchBar] in
                    searchBar?.searchTextField.resignFirstResponder()
                    
                    
                }).disposed(by: disposeBag)

1 Answers1

0

Presuming that searchBar is the actual searchBar on the UISearchController...

You have to call searchBar.resignFirstResponder() and also for iOS 13 and above I have found that the cancel button won't disappear without calling searchBar.showsCancelButton = false as well.

Furthermore I recommend to pass a weak instance of the searchBar or your code might leak. Therefore here's how I would write it:

searchBar.rx
   .cancelButtonClicked
   .asDriver(onErrorJustReturn: ())
   .drive(onNext: { [weak searchBar] in
      searchBar?.resignFirstResponder()
      searchBar?.showsCancelButton = false    
   })
   .disposed(by: disposeBag)
erik_m_martens
  • 496
  • 3
  • 8