#UI Caveats
http://stackoverflow.com/questions/19927542/ios7-backgroundimage-for-uisearchbar
//clear the transparent background when search bar promot
[self.searchDisplayController.searchBar setBackgroundImage:[self imageWithColor:[UIColor yourColor]]
forBarPosition:0
barMetrics:UIBarMetricsDefault];
#Custom Search in Nav bar:
- (void)prepareSearchControl{
//presist nav bar items
leftButton = self.navigationItem.leftBarButtonItem;
rightButton = self.navigationItem.rightBarButtonItem;
// set current navigation title view to be search bar.
titleView = self.navigationItem.titleView;
// set up searchDisplayController
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchBar.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
//set up frame -> this is not needed if you set displayInNavgiationBar -> YES.
self.searchDisplayController.searchResultsTableView.frame = self.tableView.frame;
//custom tint color and fonts
//tint color would aslo affect the color of the search box
self.searchDisplayController.searchBar.tintColor = BASE_COLOR;
//set cancel font color to be white
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],UITextAttributeTextShadowOffset,nil] forState:UIControlStateNormal];
}
##when search button clicked
swape the current navigtation item title to searchbar.
-(IBAction)searchButtonClicked:(UIBarButtonItem *)sender
{
self.navigationItem.titleView = self.searchDisplayController.searchBar;
[self.searchDisplayController.searchBar becomeFirstResponder];
self.navigationItem.leftBarButtonItem = nil; //set left button to nil
self.navigationItem.rightBarButtonItem = nil; // set right button to nil, leave more space
}
#when search starts
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[self.searchDisplayController.searchBar setShowsCancelButton:YES animated:YES];
// add subviews
[self.view addSubview:self.searchDisplayController.searchResultsTableView];
}
#when search done
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
[self.searchDisplayController.searchBar setShowsCancelButton:NO animated:YES];
//restore back those bar button items
self.navigationItem.leftBarButtonItem = leftButton;
self.navigationItem.titleView = titleView;
self.navigationItem.rightBarButtonItem = rightButton;
}
#When switch between views.
##handle check if current search and display controler is active
- (void)viewWillAppear:(BOOL)animated{
if (self.searchDisplayController.isActive) {
self.navigationItem.titleView = self.searchDisplayController.searchBar;
self.navigationItem.rightBarButtonItem = nil;
[self.searchDisplayController.searchBar setShowsCancelButton:YES animated:YES];
}
}