当用户在TableView的搜索栏中键入内容时,我正在尝试自动重新加载列表。
我尝试使用下面的代码来执行此操作。我可以获取列表,但是即使我在搜索栏中键入内容,也不会“过滤”结果。
class UsersTableViewController: UITableViewController, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
//update the search results
filterContent(searchText: self.searchController.searchBar.text!)
}
@IBOutlet var usersTableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
var databaseRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
databaseRef = Database.database().reference()
let usersRef = databaseRef.child("users")
let query = usersRef.queryOrdered(byChild: "email")
query.observe(.childAdded, with: {(snapshot) in
self.usersArray.append((snapshot.value as? NSDictionary?)!)
//insert the rows
self.usersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)
}) { (error) in
print(error.localizedDescription)
}
print("HOLAAAAAAAAAAA")
print(self.usersArray)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if ((searchController.isActive) && (searchController.searchBar.text != "")){
return filteredUsers.count
}
return self.usersArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let user: NSDictionary
if ((searchController.isActive) && (searchController.searchBar.text != "")){
user = filteredUsers[indexPath.row]!
}else{
user = self.usersArray[indexPath.row]!
}
cell.textLabel?.text = user["email"] as? String
cell.detailTextLabel?.text = user["name"] as? String
return cell
}
func filterContent(searchText: String){
self.filteredUsers = self.usersArray.filter({ user in
let userEmail = user!["email"] as? String
return (userEmail != nil)
})
tableView.reloadData()
}
}
在用户开始键入时,我期望得到的结果是,列表应该仅显示与搜索栏中的字符串匹配的搜索。但是它没有这样做。