搜索栏的新功能。
工作:
[String]“firstname”在搜索时返回正确的值。如果我有3个人以“名字”开头的“G”(例如)表重新加载3个单元格。
问题:
虽然表重新加载了“firstname”的正确单元格值,但users.append(user)返回nil,并且错误的名称被加载到tableview上。
援助:
如何在搜索完成后将正确的名称加载到tableview?
这是我的代码:
func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String)->Void {
FIRDatabase.database().reference().child("users").queryOrdered(byChild: "firstname").queryStarting(atValue: textSearched).queryEnding(atValue: textSearched+"\u{f8ff}").observe(.value, with: { snapshot in
var users = [User]()
let user = User()
print(user)
for _ in snapshot.children.allObjects as! [FIRDataSnapshot] {
if let dictionary = snapshot.value as? [String: AnyObject]{
user.lastname = dictionary["firstname"] as? String
users.append(user)
}
}
self.users = users
let search = searchCell()
search.firstName.text = user.firstname
self.attempReloadOfTable()
}, withCancel: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! searchCell
var user = User()
user = users[indexPath.row]
if let id = user.id{
let ref = FIRDatabase.database().reference().child("users").child(id)
ref.observe(.value, with: { (snapshot) in
cell.lastName.text = user.lastname
cell.firstName.text = user.firstname
})
}
return cell
}
答案 0 :(得分:0)
你的问题是在它与块中的用户数据绑定之前返回了单元格。因为FIRBase结果查询块中的代码将在return cell
执行后执行。
我编辑了你的代码:
func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String)->Void {
FIRDatabase.database().reference().child("users").queryOrdered(byChild: "firstname").queryStarting(atValue: textSearched).queryEnding(atValue: textSearched+"\u{f8ff}").observe(.value, with: { snapshot in
var users = [User]()
for _ in snapshot.children.allObjects as! [FIRDataSnapshot] {
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.lastname = dictionary["firstname"] as? String
print(user)
users.append(user)
}
}
self.users = users
let search = searchCell()
search.firstName.text = user.firstname
self.attempReloadOfTable()
}, withCancel: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! searchCell
let user = users[indexPath.row]
cell.lastName.text = user.lastname
cell.firstName.text = user.firstname
return cell
}
希望它对你有用。