ios - 为什么我的搜索结果仅在我开始输入后才显示?

标签 ios swift xcode swift5 xcode11

我正在我的应用程序中实现搜索机制,但遇到了问题。我可以很好地搜索,并且数组中的所有成员都会显示出来,但这仅在我输入内容后才会发生。当 View 加载时,什么也没有出现。只有当我开始打字时,才会发生任何事情。我不太确定出了什么问题,所以如果有人能帮助我那就太好了。谢谢!

import UIKit
import Firebase
import FirebaseFirestore

class FindUsersTableViewController: UITableViewController, UISearchBarDelegate {

    @IBOutlet var findUsersTableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    private let database = Firestore.firestore()
               private lazy var usersReference = database.collection("users")

               private let cellReuseIdentifier = "Cell"
               // This is the array that will keep track of your users, you will use it to populate your table view data:
    var usersArray = [String]()
               var filteredUsers: [String]!



    override func viewDidLoad() {
        super.viewDidLoad()

        filteredUsers = usersArray

                // Set your table view datasource and delegate:
                searchBar.delegate = self
                Firestore.firestore().collection("users").getDocuments { (snapshot, error) in
                    if let snapshot = snapshot { // don't force unwrap with !
                        for doc in snapshot.documents {
                            if let username = doc.get("username") as? String {
                                self.usersArray.append(username)
                                print(self.usersArray)

                            }
                        }
                    } else {
                        if let error = error {
                            print(error)
                        }
                    }
                }



            }



            // MARK: UITableViewDataSource methods

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

            override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                // Returns the number of users in your array:
                return filteredUsers.count

            }

            override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
                // Configure your cell here via your users array:
                cell.textLabel?.text = filteredUsers[indexPath.row]
                return cell
            }

            // MARK: UITableViewDelegate methods

            override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
                return UITableView.automaticDimension
            }


            func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
                filteredUsers = []

                if searchText == "" {
                    filteredUsers = usersArray
                }
                else {
                for info in usersArray {
                    if info.lowercased().contains(searchText.lowercased()) {
                        filteredUsers.append(info)
                    }
                }

            }
          self.tableView.reloadData()
    }
        }

最佳答案

您必须告诉 TableView 在检索数据后加载数据:

override func viewDidLoad() {
    super.viewDidLoad()

    // Set your table view datasource and delegate:
    searchBar.delegate = self
    Firestore.firestore().collection("users").getDocuments { (snapshot, error) in
        if let snapshot = snapshot { // don't force unwrap with !
            for doc in snapshot.documents {
                if let username = doc.get("username") as? String {
                    self.usersArray.append(username)
                    print(self.usersArray)
                }
            }               

            // update the filteredUsers array
            filteredUsers = usersArray

            // tell the table view to reload the data here
            DispatchQueue.main.async {
                findUsersTableView.reloadData()
            }

        } else {
            if let error = error {
                print(error)
            }
        }
    }

}

关于ios - 为什么我的搜索结果仅在我开始输入后才显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62415191/

相关文章:

ios - 将 JSON 提要转换为 NSDictionary

ios - Twitter/Fabric 登录按钮未按预期运行

swift - 快速使用 Metal 拍摄当前屏幕的快照

ios - Swift 对象永远无法将值放入其中

ios - Visual Studio 远程构建失败,出现错误 - 1

iphone - UIWebView 不调用 stringbyAppendingJavascript 函数

ios - NSUserDefaults 返回空数组

ios - 在 Swift 中子类化 Parse 的 PFUser

ios - 使用自定义维度重新排序 Collection View Cell 时出现问题

ios 以编程方式推送 Controller View ,无需 Storyboard或 xib