搜索控制器 - 我不希望在用户尚未开始键入时显示数据



]我在我的应用程序中构建了一个SearchViewController,它只是搜索用户。

一切都很好,除了当我进入视图控制器时,它甚至在我开始搜索之前就会显示Firebase数据库中的每个用户?我希望表格视图在我键入至少 2 个字母之前不显示结果。有人知道我可以实现这一点吗?

这是我的代码:

class FollowUsersTableViewController: UITableViewController ,UISearchResultsUpdating, UISearchControllerDelegate{
//    @IBOutlet var followUsersTableView: UITableView!
func updateSearchResults(for searchController: UISearchController) {
searchController.searchResultsController?.view.isHidden = false
filterContent(searchText: self.searchController.searchBar.text!)
self.tableView.reloadData()
}
private var viewIsHiddenObserver: NSKeyValueObservation?
let searchController = UISearchController(searchResultsController: nil)
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
var loggedInUser: User?
var databaseRef = Database.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
//large title
self.title = "Discover"
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.prefersLargeTitles = true
} else {
// Fallback on earlier versions
}
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
self.searchController.delegate = self;
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
databaseRef.child("profile").queryOrdered(byChild: "username").observe(.childAdded, with: { (snapshot) in
let key = snapshot.key
let snapshot = snapshot.value as? NSDictionary
snapshot?.setValue(key, forKey: "uid")
if(key == self.loggedInUser?.uid) {
print("Same as logged in user, so don't show!")
} else {
self.usersArray.append(snapshot)
//insert the rows
self.tableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
self.tableView.reloadData()
} 
}) { (error) in
print(error.localizedDescription)
}
// 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) as! FollowTableViewCell
let user : NSDictionary?
if searchController.isActive && searchController.searchBar.text != ""{
user = filteredUsers[indexPath.row]
}
else
{
user = self.usersArray[indexPath.row]
}
cell.title?.text = user?["username"] as? String
let url = URL(string: user?["photoURL"] as! String)!
cell.userImage?.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "user_male"), options: .progressiveDownload, completed: nil)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let arr = self.searchController.isActive ? self.filteredUsers : self.usersArray
self.performSegue(withIdentifier: "user", sender: arr[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let dest = segue.destination as! UserProfileViewController
let obj = sender as![String:Any]
dest.selectedUser = obj
}
func filterContent(searchText:String)
{
if searchText != ""{
self.filteredUsers = self.usersArray.filter{ user in
let username = user!["username"] as? String
return(username?.lowercased().contains(searchText.lowercased()))! 
}
}
}

那么有没有人对我如何做到这一点有任何提示? 这是我得到的错误

在你的 numberOfRowsInSection 中,你返回的是 self.usersArray.count。 如果不显示所有结果,只需返回 0,则不会显示任何结果。

如果要在输入至少 2 个字符时显示搜索,请使用 searchBar.text 的 count 属性

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" && searchController.searchBar.text.count >= 2 {
return filteredUsers.count
}
return 0
}

在你的原始代码中:

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
}

您返回self.userArray.count,因此这可能解释了为什么它在开始时显示整个未过滤的数组,而您的搜索栏中没有任何文本输入。

我还注意到您的filterContent(searchText:String)函数尚未在您的代码中调用。

但我认为当您不想更改结果表时,return self.usersArray.count行可以作为默认返回值,因为当表为空时,当已经输入了 1 或 2 个字母时,用户可能会看起来不正常。

在代码的另一部分:

self.tableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)

我认为当使用insertRow时,不再需要self.tableView.reloadData()。 🤔

关于崩溃/错误:

在代码块中:

if(key == self.loggedInUser?.uid) {
print("Same as logged in user, so don't show!")
} else {
self.usersArray.append(snapshot)
//insert the rows
self.tableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
self.tableView.reloadData()
} 

而不是self.tableView.reloadData()

请尝试:

if(key == self.loggedInUser?.uid) {
print("Same as logged in user, so don't show!")
} else {
self.usersArray.append(snapshot)
//insert the rows
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
self.tableView.endUpdates()
} 

这是为了明确地让表视图控制器知道您正在开始编辑/更改内容。请注意,使用beginUpdates()总是与endUpdates()配对,不应与reloadData()一起使用。

最新更新