My UISearchBar moves to top (animated) --> want to disable

故事扮演 提交于 2020-01-14 08:05:29

问题


I want implement an UISearchBar on my tableView.

My code (in viewDidLoad) :

self.searchController = UISearchController(searchResultsController: nil)
self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.searchBar.autocapitalizationType = .None
self.searchController.searchBar.autocorrectionType = .No

self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = false

self.tableView.tableHeaderView = self.searchController.searchBar

When I click on the searchBar, this one move to top, like it wants hide the navigationBar:

I searched on many posts for an answer but nothing works. I want to disable this animation so that the searchBar doesn't move.


回答1:


You can think of the UISearchController as being presented modally when you start searching. This would work fine if you had a usual UINavigationController setup, however in a more "customized" UI like yours you may run into issues like the search controller attaching to a wrong view, etc.

I would suggest not to use UISearchController in your case and use a separate UISearchBar initialised with the rest of your interface (probably in a storyboard?), and then do the search manually. Implement the UISearchBarDelegate and add your own UITableView for the search results, if you can't simply filter your content in place.

Although looks like you have a tableView var — you could simply add another property, similar to the one you use as a UITableViewDataSource and store filtered data there. So whenever you have something in the UISearchBar you simply use a filtered data source when reloading table view data. For instance:

var data: [String]
var filteredData: [String]

And then use filteredData in the UITableViewDataSource:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

...

And then do something like this in the UISearchBarDelegate:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    // Filter the data you have. For instance:
    filteredData = data.filter({$0.rangeOfString(searchText).location != NSNotFound})
    tableView.reloadData()
}



回答2:


You should be able to prevent this by setting:

self.searchController.hidesNavigationBarDuringPresentation = false



回答3:


Paste this line in your viewDidLoad of presenting controller: self.extendedLayoutIncludesOpaqueBars = true



来源:https://stackoverflow.com/questions/37408212/my-uisearchbar-moves-to-top-animated-want-to-disable

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