ios ios - 1 month ago 13
Objective-C Question

how to add search bar under the navigation title

please see my screen shot i need thisthis is the previous output before adding imageI need the search bar under the navigation title how to do that programmatically or via story board.

UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,30, 250,44)];
searchBar.placeholder = @"Search";
UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc]initWithCustomView:searchBar];
searchBarItem.tag = 123;
searchBarItem.customView.hidden = YES;
searchBarItem.customView.alpha = 0.0f;
self.navigationItem.leftBarButtonItem = searchBarItem;
self.navigationItem.title = @"locations";

Answer

You have added the search bar as UIBarButtonItem, thats why it is not visible.

If you want to display the search bar in place of the title view of navigation bar the use this code

Code to show navigation bar in place of Title of Navigation :

UISearchBar *searchBar = [[UISearchBar alloc]init];
searchBar.tintColor = [UIColor grayColor];
searchBar.backgroundColor = [UIColor redColor];
searchBar.placeholder = @"Search";
self.navigationItem.titleView = searchBar;

Output :

enter image description here

Code to show navigation bar below the Navigation bar:

UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 64)];
searchBar1.tintColor = [UIColor grayColor];
searchBar1.backgroundColor = [UIColor redColor];
searchBar1.placeholder = @"Search";
[self.view addSubview:searchBar1];

UPDATE :

self.navigationController.navigationBar.barTintColor = [UIColor redColor];
searchBar1.searchBarStyle = UISearchBarStyleMinimal;

UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 64)];
searchBar1.tintColor = [UIColor grayColor];
searchBar1.searchBarStyle = UISearchBarStyleMinimal;
searchBar1.backgroundColor = [UIColor redColor];
searchBar1.placeholder = @"Search";
[self.view addSubview:searchBar1];

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

Output :

enter image description here

Updated output

To customize the textField :

UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 64)];
searchBar1.tintColor = [UIColor grayColor];
searchBar1.searchBarStyle = UISearchBarStyleMinimal;
searchBar1.backgroundColor = [UIColor redColor];
searchBar1.placeholder = @"Search";
[self.view addSubview:searchBar1];

[searchBar1 setSearchFieldBackgroundImage:[UIImage imageNamed:@"text-input.png"] forState:UIControlStateNormal];

The image I have used is of height 30 pixel like the search bar's text field.

here is the image :

enter image description here

And output :

enter image description here Hope it helps ...

Happy coding ...

updated output