如何防止search栏在滚动消失? iOS Swift

我正在创build一个联系应用程序。 我有一个滚动条在我的表视图的顶部。

你看到一个搜索栏

当我向下滚动search栏消失。

现在你不用

如何防止search栏在滚动消失? 我希望它像第一张照片一样始终保持在页面顶部。

这是我的故事板的图片:

在这里输入图像说明

这是我的视图控制器代码,如果解决scheme不在故事板中:

class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { //manages search bar var searchController:UISearchController! var contacts = [Contact]() //array to hold contacts that match the search results var filteredContacts = [Contact]() override func viewDidLoad() { super.viewDidLoad() //initialize the defaults manager class NSUserDefaultsManager.initializeDefaults() //search controller searchController = UISearchController(searchResultsController: nil) searchController.searchBar.sizeToFit() tableView.tableHeaderView = searchController.searchBar definesPresentationContext = true searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false //load the contacts title = "Contacts" tableView.backgroundView = UIImageView(image: UIImage(named: "valblur15")) contacts = [Contact]() let api = ContactAPI() api.loadContacts(didLoadContacts) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //reload the table view to check for new contacts tableView.reloadData() //set the color of the nav bar to valbruna yellow navigationController?.navigationBar.backgroundColor = UIColor(red: 254.0/255.0, green: 196.0/255.0, blue: 37.0/255.0, alpha: 0.95) } //MARK: -Helper Methods // Uupdate searching results func updateSearchResultsForSearchController(searchController: UISearchController) { let searchText = searchController.searchBar.text filterContentForSearchText(searchText) tableView.reloadData() } func filterList() { // should probably be called sort and not filter //sort contacts from az contacts.sort() { $0.name < $1.name } //remove contacts whose locations are nil contacts = contacts.filter() { $0.location != "nil"} //remove contacts whose titles phone email and department are all nil contacts = contacts.filter() { if($0.title != "" || $0.phone != "" || $0.email != "" || $0.department != ""){ return true } return false } tableView.reloadData() } func didLoadContacts(contacts: [Contact]){ self.contacts = contacts filterList() tableView.reloadData() } //MARK: -Table View //set number opf sections in table view override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //delegeate that tells tabel view how many cells to have override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return size of array //if searching show count of filtered contacts if (searchController.active){ return self.filteredContacts.count }else{ return self.contacts.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("customcell") as! CustomCell //from the customcell class //change color of cell text label cell.textLabel?.textColor = UIColor.blackColor() cell.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.8) let contact : Contact //if users is searching then return filtered contacts if (searchController.active){ contact = self.filteredContacts[indexPath.row] }else{ contact = self.contacts[indexPath.row] } //handel assignment of text cell.textLabel?.text = contact.name //retrieve from customcell class cell.contact = contact return cell } //MARK: -Search func filterContentForSearchText(searchText: String, scope: String = "Title") { self.filteredContacts = self.contacts.filter({( contact: Contact) -> Bool in //filters contacts array var categoryMatch = (scope == "Title") var stringMatch = contact.name?.rangeOfString(searchText) return categoryMatch && (stringMatch != nil) }) } func searchDisplayController(controller: UISearchController, shouldReloadTableForSearchString searchString: String!) -> Bool { self.filterContentForSearchText(searchString, scope: "Title") return true } func searchDisplayController(controller: UISearchController, shouldReloadTableForSearchScope searchOption: Int) -> Bool { self.filterContentForSearchText(self.searchController!.searchBar.text, scope: "Title") return true } //MARK: -Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "detailview"){ let cell = sender as! CustomCell let detailView = segue.destinationViewController as! DetailViewController detailView.preContact = cell.contact } } } 

编辑1:

Ryosuke Hiramatsu的解决scheme是基于以下步骤:

  1. 命令X表格视图。
  2. 添加一个视图。
  3. 将V视图切换到新视图。
  4. 在视图控制器中,将UITableViewController更改为UITableView
  5. 向视图控制器名为table view添加一个sockets。
  6. 删除表视图函数中的覆盖。
  7. 删除这行代码:tableView.tableHeaderView = searchController.searchBar
  8. 回到故事板并将search栏移出表格视图。 它会出现在表格视图的后面。
  9. 向下移动表视图和search栏。
  10. 添加必要的约束。

我的看法现在看起来像这样:

2个搜索栏

当我向下滚动时:

1个搜索栏

我的故事板:

故事板编辑1

最后,我更新的视图控制器代码:

 import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { @IBOutlet var tableView: UITableView! //manages search bar var searchController:UISearchController! var contacts = [Contact]() //array to hold contacts that match the search results var filteredContacts = [Contact]() override func viewDidLoad() { super.viewDidLoad() //initialize the defaults manager class NSUserDefaultsManager.initializeDefaults() //search controller searchController = UISearchController(searchResultsController: nil) searchController.searchBar.sizeToFit() definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false //load the contacts title = "Valbruna Contacts" tableView.backgroundView = UIImageView(image: UIImage(named: "valblur15")) contacts = [Contact]() let api = ContactAPI() api.loadContacts(didLoadContacts) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //reload the table view to check for new contacts tableView.reloadData() //set the color of the nav bar to valbruna yellow navigationController?.navigationBar.backgroundColor = UIColor(red: 254.0/255.0, green: 196.0/255.0, blue: 37.0/255.0, alpha: 0.95) } //MARK: -Helper Methods // Uupdate searching results func updateSearchResultsForSearchController(searchController: UISearchController) { let searchText = searchController.searchBar.text filterContentForSearchText(searchText) tableView.reloadData() } func filterList() { // should probably be called sort and not filter //sort contacts from az contacts.sort() { $0.name < $1.name } //remove contacts whose locations are nil contacts = contacts.filter() { $0.location != "nil"} //remove contacts whose titles phone email and department are all nil contacts = contacts.filter() { if($0.title != "" || $0.phone != "" || $0.email != "" || $0.department != ""){ return true } return false } tableView.reloadData() } func didLoadContacts(contacts: [Contact]){ self.contacts = contacts filterList() tableView.reloadData() } //MARK: -Table View //set number opf sections in table view func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //delegeate that tells tabel view how many cells to have func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return size of array //if searching show count of filtered contacts if (searchController.active){ return self.filteredContacts.count }else{ return self.contacts.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("customcell") as! CustomCell //from the customcell class //change color of cell text label cell.textLabel?.textColor = UIColor.blackColor() cell.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.8) let contact : Contact //if users is searching then return filtered contacts if (searchController.active){ contact = self.filteredContacts[indexPath.row] }else{ contact = self.contacts[indexPath.row] } //handel assignment of text cell.textLabel?.text = contact.name //retrieve from customcell class cell.contact = contact return cell } //MARK: -Search func filterContentForSearchText(searchText: String, scope: String = "Title") { self.filteredContacts = self.contacts.filter({( contact: Contact) -> Bool in //filters contacts array var categoryMatch = (scope == "Title") var stringMatch = contact.name?.rangeOfString(searchText) return categoryMatch && (stringMatch != nil) }) } func searchDisplayController(controller: UISearchController, shouldReloadTableForSearchString searchString: String!) -> Bool { self.filterContentForSearchText(searchString, scope: "Title") return true } func searchDisplayController(controller: UISearchController, shouldReloadTableForSearchScope searchOption: Int) -> Bool { self.filterContentForSearchText(self.searchController!.searchBar.text, scope: "Title") return true } //MARK: -Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "detailview"){ let cell = sender as! CustomCell let detailView = segue.destinationViewController as! DetailViewController detailView.preContact = cell.contact } } 

}

我现在的问题是,只有第一个search栏是静止的,它不search时,我input它。 第二个search栏在滚动中消失。 另外,当我点击一个名称不再延续到下一个视图。

问题是视图层次结构。

你的故事板是这样的:

在这里输入图像说明

search栏被添加到TableView上。

正确的等级是这样的:

在这里输入图像说明

您将UITableViewController更改为UIViewController,并在注意查看层次的同时追加SearchDisplayController。

它会工作:)

iOS9

有同样的问题。 我以编程方式添加了search栏。 这是我如何修复我的。 可能在未来的帮助:)

我在tableview的viewForHeaderInSection上添加了viewForHeaderInSection而不是添加到tableView.tableHeaderView

删除这条线,如果存在。 tableView.tableHeaderView = searchController.searchBar

然后在tableview的代表上实现这个。

 func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return self.searchController.searchBar } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return searchController.searchBar.frame.height } 

希望能帮助到你 !

我觉得问题出现是因为你已经添加了search栏作为表头视图。

 tableView.tableHeaderView = searchController.searchBar 

尝试在self.view中添加search栏,如下所示:

 self.view. addsubview("Yore search bar") 

希望这会解决你的问题

你正在添加一个UISearchController作为你的UITableViewheaderView 。 表视图标题不是“粘滞”的,用户滚动浏览表格时滚动单元格。 考虑创build一个节头,并在viewForHeaderInSection添加你的UISearchController