Adding buttons inside UISearchBar

12,074

Solution 1

Edit :

As stated by @NicolasMiari in the comments :

This no longer works post-iOS 7, since the bookmarks button is rendered inside the bar's input text field.


For the button inside the search bar, you can use the bookmark button and change its image. You simply go to your storyboard (if you use one), select the search bar, and activate the option "Shows Bookmarks Button". Then, in your code, set the image you want :

[_searchBar setImage:[UIImage imageNamed:@"My-Custom-Image"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];

You can detect a click on this button with the following delegate method :

- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar {

    NSLog(@"click");
}

Solution 2

Swift 4

class ViewController: UIViewController {

   var searchController = UISearchController(searchResultsController: nil)

   override func viewDidLoad() {
      searchController.delegate = self 
      searchController.searchBar.delegate = self 
      searchController.searchBar.showsBookmarkButton = true
      searchController.searchBar.setImage(UIImage(named: "myImage"), for: .bookmark, state: .normal)
   }

}

extension ViewController: UISearchBarDelegate {

   func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
      print("click")
   }

}

Solution 3

The fastest way to add a button in UISearchBar is to update the bookmark button like this:

[self.searchDisplayController.searchBar setImage:[UIImage imageNamed:@"customImage.png"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];

If you need to adjust the offset,

[self.searchDisplayController.searchBar setPositionAdjustment:UIOffsetMake(-10, 0) forSearchBarIcon:UISearchBarIconBookmark];

Don't forget to activate the option "Shows Bookmarks Button" in story board.

Share:
12,074
Naveen Thunga
Author by

Naveen Thunga

iPhone, iPad App developer.

Updated on June 28, 2022

Comments

  • Naveen Thunga
    Naveen Thunga almost 2 years

    enter image description here

    I want to add a button (bar) inside a UISearchbar and another one just outside the UISearchbar as shown in the image. Any help on this appreciated.

    Thanks in advance Naveen

  • Nicolas Miari
    Nicolas Miari over 8 years
    This no longer works post-iOS 7, since the bookmarks button is rendered inside the bar's input text field.
  • heyfrank
    heyfrank about 6 years
    This is working in iOS 10 and 11. See Swift 4 oneliner from Strat Aguilar: searchBar.setImage(UIImage(named: "myImage"), for: UISearchBarIcon.bookmark, state: .normal)