How do I put UISearchController Searchbar onto navigation bar with code
如果我将 ViewController 嵌入到导航栏中,
1 2 3 4 5 6 7 8 9 10 11 | resultSearchController = UISearchController(searchResultsController: locationSearchTable) resultSearchController?.searchResultsUpdater = locationSearchTable let searchBar = resultSearchController!.searchBar searchBar.sizeToFit() searchBar.delegate = self let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y:0, width: 375, height: 64)) self.view.addSubview(navBar) //navBar.topItem = resultSearchController?.searchBar self.navigationItem.titleView = resultSearchController?.searchBar |
创建一个
将搜索控制器搜索栏添加到 UINavigationItem 作为 titleView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class SearchViewController: UIViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate { var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() self.addNavigationbar() } func addNavigationbar() { let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 60)) self.view.addSubview(navBar) let navigationItem = UINavigationItem(title:"") self.searchController = searchControllerWith(searchResultsController: nil) navigationItem.titleView = self.searchController.searchBar navBar.setItems([navigationItem], animated: false) self.definesPresentationContext = true } func searchControllerWith(searchResultsController: UIViewController?) -> UISearchController { let searchController = UISearchController(searchResultsController: searchResultsController) searchController.delegate = self searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = true return searchController } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class UIViewController: UIViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate { var searchController : UISearchController! override func viewDidLoad() { super.viewDidLoad() self.searchController = UISearchController(searchResultsController: nil) self.searchController.searchResultsUpdater = self self.searchController.delegate = self self.searchController.searchBar.delegate = self self.searchController.hidesNavigationBarDuringPresentation = false self.searchController.dimsBackgroundDuringPresentation = true self.navigationItem.titleView = searchController.searchBar self.definesPresentationContext = true } func updateSearchResults(for searchController: UISearchController) { } } |