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:
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)
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With