Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show search bar with action (bar item)

I have a problem with search bar. I need to create a table view with a search button in the right corner, and when I click on it, it should show the search bar.

My code is here:

// Search controller
searchController = ({
    let controller = UISearchController(searchResultsController: nil)
    controller.delegate = self
    controller.searchBar.delegate = self
    controller.searchResultsUpdater = self
    controller.dimsBackgroundDuringPresentation = false         
    controller.hidesNavigationBarDuringPresentation = true
    controller.searchBar.sizeToFit()
    return controller
})()

And here is action:

// Search action
@IBAction func search(sender: UIBarButtonItem) {
    print("Open search")
    searchController.active = true
    if searchController.searchBar.isFirstResponder() == false {
        searchController.searchBar.becomeFirstResponder()
    }
}

When I click on the button, nothing happens (only prints text in console), and what I want is in the image below:

Show search

like image 276
Nikola Avatar asked Aug 02 '16 19:08

Nikola


2 Answers

Your class needs to conform to a UISearchBarDelegate, I'm not sure if you've done that already. Also make sure you present the search view

From Apple's Docs:

The UISearchBarDelegate protocol defines the optional methods you implement to make a UISearchBar control functional. A UISearchBar object provides the user interface for a search field on a bar, but it’s the application’s responsibility to implement the actions when buttons are tapped. At a minimum, the delegate needs to perform the actual search when text is entered in the text field.

Here's a sample from my app

@IBAction func searchAction(sender: UIBarButtonItem) {
    // Create the search controller and specify that it should present its results in this same view        
    searchController = UISearchController(searchResultsController: nil) 

    // Set any properties (in this case, don't hide the nav bar and don't show the emoji keyboard option)
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.keyboardType = UIKeyboardType.ASCIICapable

    // Make this class the delegate and present the search
    self.searchController.searchBar.delegate = self
    presentViewController(searchController, animated: true, completion: nil)
}
like image 167
Jason Avatar answered Oct 12 '22 07:10

Jason


Old question, but want to add a new answer (maybe things changed since the original answer from 2016).

Simply call this on the view controller, assuming you already set up the search controller. No need to conform to UISearchBarDelegate:

Swift 5

present(searchController, animated: true, completion: nil)
like image 41
Sean Avatar answered Oct 12 '22 07:10

Sean