简体   繁体   中英

iOS - How to add UISearchController.searchBar to a controller without a UITableView?

I've looked for tutorials of UISearchController and all of them are implemented this way:

├── MainTableViewController(UITableViewController*)
   ├── SearchController(UISearchController*)
   └── ResultTableViewController(UITableViewController*)

In this way, the SearchController.searchBar can be displayed at the top of the view simply by

MainTableViewController.tableView.tableHeaderView = SearchController.searchBar;

How can I add the searchBar to the top of a controller which is not a UITableViewController ?

In your storyboard select your viewController and open Utilities(top right icon) and search for UISearchBar . Now drag the UISearchBar into your viewController and set frame/constraints. And make a coonection for added searchbar to your viewController class.

In side your viewController class set delegate for search bar

override func viewDidLoad()
{
  super.viewDidLoad()
  searchBar.delegate = self          
}

Now implement searchBar:textDidChange method

func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
{

}

It works just fine without a table view. The UISearchDisplayController instance needs a searchResultsDatasource and delegate, which are really UITableView datasource and delegate.

Since these implementations are present in UITableViews, they are often reused as the implementations for the search controller, but that needn't be the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM