【问题标题】:Why do the results of my search only show up once I begin typing?为什么我的搜索结果只有在我开始输入后才会显示?
【发布时间】:2020-06-16 18:22:56
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift xcode swift5 xcode11


    【解决方案1】:

    你必须告诉表格视图在你检索到数据后加载它:

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

    【讨论】:

      【解决方案2】:

      在代码中添加计算属性:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 1970-01-01
        • 2012-07-01
        • 1970-01-01
        相关资源
        最近更新 更多