Show search string with action (bar position)

I have a problem with the 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 display a 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 the 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 (it only prints text on the console), and what I want is in the image below:

Show search

+2
source share
1 answer

Your class should match UISearchBarDelegate , I'm not sure if you already did this. Also make sure you submit the search box

From Apple Docs:

UISearchBarDelegate , UISearchBar. UISearchBar , . , , .

@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)
}
+10

Source: https://habr.com/ru/post/1687446/


All Articles