How do I put UISearchController Searchbar onto navigation bar with code
如果我将 ViewController 嵌入到导航栏中,navigationItem.titleView.resultSearchController?.searchBar 会将搜索栏放入导航栏中。但是,我用代码创建了一个 UISearchController 和一个 UINavigationBar。这一次,navBar 出现了,但 searchBar 没有出现。
1
2 3 4 5 6 7 8 9 10 11 |
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable let searchBar = resultSearchController!.searchBar let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y:0, width: 375, height: 64)) |
navBar.topItem = resultSearchController?.searchBar 不起作用,因为 topItem 是字符串值,而 resultSearchController?.searchBar 是 UIView 类型。我怎样才能达到同样的效果?
创建一个 UINavigationItem 实例并将其添加到创建的导航栏。
将搜索控制器搜索栏添加到 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() { func addNavigationbar() { let navigationItem = UINavigationItem(title:””) navBar.setItems([navigationItem], animated: false) func searchControllerWith(searchResultsController: UIViewController?) -> UISearchController { let searchController = UISearchController(searchResultsController: searchResultsController) 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() { self.searchController = UISearchController(searchResultsController: nil) self.searchController.searchResultsUpdater = self self.searchController.hidesNavigationBarDuringPresentation = false self.navigationItem.titleView = searchController.searchBar self.definesPresentationContext = true func updateSearchResults(for searchController: UISearchController) { } } |
- 此代码中没有创建导航栏。假设您将 VC 嵌入导航栏,则此代码有效。我的问题是如何使 searchBar 成为我用代码创建的 navBar 的 titleView
来源:https://www.codenong.com/45757002/