我使用以下教程让我的用户搜索“位置”,然后表视图将根据搜索文本过滤结果。我甚至添加了“范围”,因此用户可以在“全部”和“食物”之类的东西之间进行过滤。这非常有效。然而问题是,它说在搜索栏下面的食物范围选项卡上,搜索栏文本为空,它将默认返回显示所有结果,即使我只是想让它显示所有的食物结果,而不是全部全部结果。其他范围(公共汽车和停车)也会出现同样的问题。当我开始输入时,它可以工作(将从Food范围获取结果)。如果文本为空而不是当前正在发生的事情,我怎样才能显示所有的Food范围结果(即使我在Food scape选项卡上显示所有范围)?
以下是我的代码的相关部分......
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchBar.scopeButtonTitles = ["All", "Food", "Bus", "Parking"]
tableView.tableHeaderView = searchController.searchBar
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredLocations.count
}
return locations.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("campusLocationCell", forIndexPath: indexPath) as? CampusLocationTableViewCell {
let location: Location
if searchController.active && searchController.searchBar.text != "" {
location = filteredLocations[indexPath.row]
} else {
location = locations[indexPath.row]
}
cell.configureCampusLocationCell(location.locationName, locationLatitude: location.locationLatitude, locationLongitude: location.locationLongitude)
return cell
} else {
return CampusLocationTableViewCell()
}
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredLocations = locations.filter({( location : Location) -> Bool in
let categoryMatch = (scope == "All") || (location.locationCategory == scope)
return categoryMatch && location.locationName.lowercaseString.containsString(searchText.lowercaseString)
})
tableView.reloadData()
}
...扩展
extension CampusLocationsViewController: UISearchBarDelegate {
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
}
extension CampusLocationsViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
filterContentForSearchText(searchController.searchBar.text!, scope: scope)
}
}