How to animate add UISearchBar on top of UINavigationBar

后端 未结 4 1133
傲寒
傲寒 2020-12-07 08:44

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 s

4条回答
  •  一向
    一向 (楼主)
    2020-12-07 09:37

    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()
      }
    }
    

提交回复
热议问题