Почему результаты моего поиска появляются только после того, как я начинаю печатать? - PullRequest
2 голосов
/ 16 июня 2020

Я внедряю механизм поиска в свое приложение, но столкнулся с проблемой. Я могу хорошо искать, и все члены моего массива отображаются, но это происходит только после того, как я что-то напечатал. Когда представление загружается, ничего не появляется. Только когда я начинаю печатать, все происходит. Я не совсем уверен, что происходит не так, поэтому, если бы кто-нибудь мог мне помочь, это было бы fantasti c. Спасибо!

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()
    }
        }

Ответы [ 2 ]

1 голос
/ 16 июня 2020

Добавьте вычисляемое свойство в свой код:

var isFiltering: Bool {
   return searchController.isActive && !isSearchBarEmpty
}

В numberOfRowsInSection сделайте что-то вроде этого:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isFiltering {
        return filteredArray.count
    }

    return nonFilteredArray.count
}

А затем в cellForRowAt сделайте что-то вроде этого:

func tableView(_ tableView: UITableView, 
           cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
  let tableViewArray: [String]!
  if isFiltering {
    tableViewArray = filteredArray
  } else {
    tableViewArray = nonFilteredArray
  }
  cell.textLabel?.text = tableViewArray[indexPath.row]
  return cell
}

Если вам нужна дополнительная информация по теме, проверьте это:

https://www.raywenderlich.com/4363809-uisearchcontroller-tutorial-getting-started https://developer.apple.com/documentation/uikit/uisearchcontroller

1 голос
/ 16 июня 2020

Вы должны указать табличному представлению загружать данные после того, как вы их получили:

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)
            }
        }
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...