Question

I want to use a search bar button in a navigation bar to show a search bar just like Apple do in the Calendar app. The cancel button would dismiss the search bar and return the navigation bar to its former state, bar buttons, title, etc.

Using the iOS 7 property:

self.searchDisplayController.displaysSearchBarInNavigationBar = YES;

puts the search bar into the navigation bar just fine. My problem is trying to have it appear conditionally on the press of a bar button. I've tried firing this line from my button's action but no go. I've tried setActive:Animated: on the searchDisplayController

self.searchDisplayController.active = YES;

but no luck either. Any ideas or help would be appreciated.

Was it helpful?

Solution

I'm not sure if you notice, but on the Apple's calendar app when you press the search icon, it open a new UITableView with search bar. If this is what you want to do, you will have a create a UIViewController with a UITableView and a UISearchBar which inside that tableView you will be filtering the content.

If I was you, I will just hide the UISearchBar and call it whenever is needed with the button to show up.

This might work as well. Just give it a try and let me know:

In your viewWillAppear:

- (void)viewWillAppear:(BOOL)animated {

// scroll search bar out of sight
CGRect newBounds = self.tableView.bounds;
if (self.tableView.bounds.origin.y < 44) {
    newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
    self.tableView.bounds = newBounds;
}
// new for iOS 7
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:0 animated:YES];}

Now that is hidden, call this to hide it again when the search is done:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self viewWillAppear:YES];
}

and to show the searchBar with a button, then:

- (IBAction)displaySearchBar:(id)sender {
    // makes the search bar visible
    [self.searchBar becomeFirstResponder];
}

OTHER TIPS

In iOS 8 you can simply present a UISearchController and you will get the same animation as Calendar.app. Check out Apple's UICatalog sample code for an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top