我将UISearchController()添加到我的UIViewController中,如下所示:
class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
let tableData = ["Here's", "to", "the", "crazy"]
var filteredTableData = [String]()
var resultSearchController = UISearchController()
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
// Reload the table
self.tableView.reloadData()
}
... TableView函数 ...
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
我正在尝试隐藏搜索栏,换句话说,使其类似于“Notes”iPhone应用程序的搜索栏样式,您必须向下滚动tableView以显示搜索栏。有没有办法实现这个目标?就像添加一个负面约束,当ViewController加载时,它会隐藏在导航栏下面吗?
答案 0 :(得分:6)
找到一个非常简单的解决方案,默认隐藏搜索栏,我找到了答案here
我只需要在viewDidLoad()中添加这一行:
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
更新为Swift 3.0语法:
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)