Make UISearchBar dismiss like Music App

百般思念 提交于 2019-12-03 16:44:39

This is how I have achieved this. It is simple and easy.

extension UIViewController {


    func setNavigationBarItem() {

        let searchaButton = UIButton.init(frame: CGRectMake(0, 0, 30, 30))
        searchaButton.setBackgroundImage(UIImage(named: "search.png"), forState: UIControlState.Normal)
        searchaButton.addTarget(self, action: #selector(self.searchPressed), forControlEvents: UIControlEvents.TouchUpInside)


        let rightButton: UIBarButtonItem = UIBarButtonItem.init(customView: searchaButton)

        navigationItem.rightBarButtonItem = rightButton

    }


    public func searchPressed(){

        var searchController: UISearchController!

        // Create the search results view controller and use it for the UISearchController.
        let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier("SearchResultController") as! SearchResultsViewController

        // Create the search controller and make it perform the results updating.
        searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchResultsUpdater = searchResultsController
        searchController.hidesNavigationBarDuringPresentation = false

        // Present the view controller.
        presentViewController(searchController, animated: true, completion: nil)

    }

}

Note:

This code is for old swift version.

I hope this will help you.

The searchBar expands to the right because the search is being cancelled, and the cancel button is disappearing.

Instead of canceling the search and triggering that animation, simply explicitly dismiss the search controller.

You can do this by setting

searchController.active = false

To make this animation work, you'll need to understand custom UIViewController transitions. Within the UISearchBarDelegate method -searchBarCancelButtonClicked(searchBar:), you'll need to do a few things:

  1. Hide the UINavigationBar on the UISearchController dismissal
  2. Animate the UITableView to the bottom of the frame and fade out.
  3. If you're presenting search modally, ensure that you're setting the modalPresentationStyle to UIModalPresentationCurrentContext.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!