我正在尝试在我的应用程序中创建营地搜索功能。我希望用户能够在搜索栏中键入内容,并显示营地过滤器列表,以匹配他们键入的内容。现在,一个用户点击一个按钮,打开SearchCampgroundsViewController.swift
import UIKit
class SearchCampgroundsViewController: UIViewController, UISearchResultsUpdating {
let searchController = UISearchController(searchResultsController: nil)
@IBOutlet weak var tableView: UITableView!
var campgrounds: [Campground]? {
return DataProvider.sharedInstance.allCampground()
}
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
self.tableView.tableHeaderView = searchController.searchBar
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension SearchCampgroundsViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.campgrounds?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("campgroundCell")! as UITableViewCell
cell.textLabel?.text = campgrounds?[indexPath.row].facilityName ?? "NO NAME FOR THIS FACILITY"
return cell
}
}
露营地列表在表格视图中正确显示(列表长约4000项),搜索栏正确显示在表格顶部。我可以在搜索栏中键入,但结果不会被过滤。如何实现筛选?updateSearchResultsForSearchController函数需要进行哪些操作?
您需要使用在搜索栏中输入的文本(searchController.searchBar.text
)来筛选数据源(campgrounds
),然后用筛选后的数据重新加载表视图。
若要将数据源保持为计算属性,则需要定义一个新变量来保存一个已过滤露营地的数组(请参见下文)。然后,您必须引入检查,以根据搜索控制器是否处于活动状态来确定要使用哪个数据源。
或者,您可以使用单个数据源,根据需要返回一组经过过滤或未经过滤的露营地。
请注意,您需要import Foundation
才能使用rangeOfString()
。
尝试以下方法:
import Foundation
/* ... */
var filtered: [Campground]?
func updateSearchResultsForSearchController(searchController: UISearchController) {
filtered = campgrounds?.filter {
// True if facilityName contains search bar text (case-sensitive).
$0.facilityName.rangeOfString(searchController.searchBar.text!) != nil
}
tableView.reloadData()
}
/* ... */
extension SearchCampgroundsViewController: UITableViewDataSource
{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && !searchController.searchBar.text.isEmpty {
return filtered?.count ?? 0
}
return campgrounds?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("campgroundCell")! as UITableViewCell
if searchController.active && searchController.searchBar.text != "" {
cell.textLabel?.text = filtered?[indexPath.row].facilityName ?? "NO NAME FOR THIS FACILITY"
} else {
cell.textLabel?.text = campgrounds?[indexPath.row].facilityName ?? "NO NAME FOR THIS FACILITY"
}
return cell
}
}