SearchBar 在激活和输入之前不会 returns 结果

SearchBar doesn't returns results until activated and typing

我第一次加载 tableView 时看到空行。但是,如果我激活 searchBar,在 textField 中写入一些内容,即使我清除了所有文本,一切也能正常工作。我希望应用程序在没有这些额外步骤的情况下工作。但是我不明白我到底哪里出错了。

class NextTableViewCell: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate {

@IBOutlet weak var searchBar: UISearchBar!

    var ref: DatabaseReference?
    let db = Firestore.firestore()
    var messages: [Message] = []
    var filteredMessages: [Message] = []

    override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self
    tableView.dataSource = self    
    loadMessages()       
    filteredMessages = messages
}

Func loadMessages 从 Firebase 检索数据

   func loadMessages() {
    let user =  Auth.auth().currentUser?.email
    let docRef = db.collection(K.FStore.collectionName).document(user!)
    docRef.addSnapshotListener { (querySnapshot, error) in
        self.messages = []
        if let e = error {
            print(e)
        } else {
            if let snapshotDocuments = querySnapshot?.data(){
                for item in snapshotDocuments {
                    if let key = item.key as? String, let translate = item.value as? String {
                        let newMessage = Message(key: key, value: translate)
                        self.messages.append(newMessage)
                    }
                }
                DispatchQueue.main.async { [self] in
                        self.messages.sort(by:  {.key > [=12=].key})
                        self.tableView.reloadData()
                    }
                }
            }
        }
    }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredMessages.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let message = filteredMessages[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "ListVC", for: indexPath)
    cell.textLabel?.text = message.key + " - " + message.value

    
    return cell
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    
    filteredMessages = []
        
    if searchText == "" {
        
        filteredMessages = messages
        
    }else{
    
        for item in messages {
            if item.key.lowercased().contains(searchText.lowercased()){
                if let key = item.key as? String, let translate = item.value as? String {

                    let newMessage = Message(key: key, value: translate)
                    self.filteredMessages.append(newMessage)
                }
            }
         
        }
    }
    
    tableView.reloadData()

}

问题是 filteredMessages 在加载视图控制器时为空,只有在您搜索时才会填充。

由于 filteredMessages 本质上是 messages 的子集,您需要在从数据库中获取它们时将 filteredMessages 设置为 messages

尝试在您的 loadMessages() 方法中添加一行:

DispatchQueue.main.async { [self] in
    self.messages.sort(by:  {.key > [=10=].key})
    self.filteredMessages = self.messages // Add this line
    self.tableView.reloadData()
}