How to animate add UISearchBar on top of UINavigationBar

yong ho picture yong ho · Jul 6, 2014 · Viewed 30.9k times · Source

If I set the displaysSearchBarInNavigationBar = YES in viewDidLoad, the search bar will be in navigation bar when the view show up. But I want to show search bar on top of navigation bar when I touch bar button item. It's like image below

normal navigation bar: enter image description here

search bar on top of navigation bar after right bar button item clicked enter image description here

Answer

Nick Wargnier picture Nick Wargnier · Jul 23, 2015

I've modified Mark's answer a little to get it to work in IOS 8 and in swift.

class ViewController : UIViewController, UISearchBarDelegate {
  var searchBar = UISearchBar()
  var searchBarButtonItem: UIBarButtonItem?
  var logoImageView   : UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Can replace logoImageView for titleLabel of navbar
    let logoImage = UIImage(named: "logo-navbar")!
    logoImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: logoImage.size.width, height: logoImage.size.height))
    logoImageView.image = logoImage
    navigationItem.titleView = logoImageView

    searchBar.delegate = self
    searchBar.searchBarStyle = UISearchBarStyle.Minimal
    searchBarButtonItem = navigationItem.rightBarButtonItem
  }

  @IBAction func searchButtonPressed(sender: AnyObject) {
    showSearchBar()
  }


  func showSearchBar() {
    searchBar.alpha = 0
    navigationItem.titleView = searchBar
    navigationItem.setLeftBarButtonItem(nil, animated: true)
    UIView.animateWithDuration(0.5, animations: {
      self.searchBar.alpha = 1
      }, completion: { finished in
        self.searchBar.becomeFirstResponder()
    })
  }

  func hideSearchBar() {
    navigationItem.setLeftBarButtonItem(searchBarButtonItem, animated: true)
    logoImageView.alpha = 0
    UIView.animateWithDuration(0.3, animations: {
      self.navigationItem.titleView = self.logoImageView
      self.logoImageView.alpha = 1
      }, completion: { finished in

    })
  }


  //MARK: UISearchBarDelegate
  func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    hideSearchBar()
  }
}