Show search bar with action (bar item)

不想你离开。 提交于 2019-12-06 03:23:27

问题


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:


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/38729151/show-search-bar-with-action-bar-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!