44

I'm using UISearchBar when I input text on UISearchBar the keyboard shows. At that time, keyboard return key is "Search". I want to implement event when I press the keyboard search button. How can I implement the action? On UITextField it has

-(BOOL)textFieldShouldReturn:(UITextField *)textField;

But on UISearchBar it doesn't have return action.

Thank you for your helping.

Praveenkumar
  • 24,084
  • 23
  • 95
  • 173
Chenggong Jin
  • 531
  • 1
  • 4
  • 9
  • possible duplicate of [How i dismiss keyboard on tapping search button on keyboard regarding UISearchBar?](http://stackoverflow.com/questions/8558339/how-i-dismiss-keyboard-on-tapping-search-button-on-keyboard-regarding-uisearchba) – Parth Bhatt Jul 13 '13 at 09:18

4 Answers4

129

Add UISearchBarDelegate in .h

Also set SearchBar's object delegate to self.

Add this to the UISearchBarDelegate's method:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    // Do the search...
}

Swift

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
Milo
  • 5,041
  • 7
  • 33
  • 59
24

In Swift 3:

 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
 }
Kaptain
  • 1,358
  • 12
  • 20
6

The textFieldShouldReturn method is a textField delegate method and not the one you're looking for. What you need is a UISearchBarDelegate method called searchButtonClicked, have a look here.

Adis
  • 4,512
  • 2
  • 33
  • 40
0

i Used following code in swift 5. implement UISearchBarDelegate then write following code in class keyboard will automatically hide on clicking search

class sample: UIViewController, UISearchBarDelegate {

    let searchbar:  UISearchBar = {
        let sear = UISearchBar()
        sear.tintColor = Mycolor().lightgray1
        sear.backgroundColor = Mycolor().lightgray1
        sear.barTintColor =  Mycolor().lightgray1
        sear.placeholder = "Search Asset"
        sear.layer.cornerRadius = 30
        sear.barStyle = .default
        sear.backgroundImage = UIImage()

        sear.returnKeyType = .search

        // sear.addShadow(offset: CGSize(width: 10, height: 10), color: UIColor.darkGray, radius: 20, opacity: 5)

        return sear

    }()

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
}
Museer Ahamad Ansari
  • 5,414
  • 3
  • 39
  • 45
Mohammad Muddasir
  • 947
  • 10
  • 21