2
votes

I have a table view with a header that displays a UISegmentedControl and a UISearchBar. Keep in mind that I am not using a UISearchController. When I have searched the current list, and I toggle a different segment, I want to cancel the search and reload the list with the new data.

Currently I am manually clearing the search text, animating the cancel button and hiding the keyboard. But I am also doing that inside my searchBarCancelButtonClicked method.

Is there a way to programmatically cancel the search (clearing the text, hiding the keyboard, and hiding the cancel button) when only using a UISearchBar?

1

1 Answers

1
votes

No, there's no way to automatically clear the text field, hide the keyboard, etc. Even though it seems like common functionality, it's up to each developer to decide how to implement it. Apple just provides the ability to catch the event when the user taps the Cancel button.

Typically, I'll create a local function in the view controller like:

-(void)clearSearchBar:(UISearchBar *)searchBar {
    searchBar.Text = @"";
    [searchBar resignFirstResponder];
    ...
 }

Then, in searchBarCancelButtonClicked: (assuming you've created an IBOutlet for the search bar), you can do this:

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self clearSearchBar:self.searchBar];
}

You can then also call clearSearchBar: anywhere else you need to clear it.

Obviously, there's room to use categories here to avoid duplicating code.

You could also just call searchBarCancelButtonClicked: like this:

[self.searchBar.delegate searchBarCancelButtonClicked:self.searchBar];