为什么我的tableview显示搜索结果? [英] Why dosent my tableview show search results?

查看:58
本文介绍了为什么我的tableview显示搜索结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当用户键入至少2个单词时,我才尝试完成对其他用户的搜索,然后才开始在数据库中搜索(因为我不想为用户扫描整个数据库).我在使用2个字母进行搜索时遇到了一些问题,但是我想我已经得到了代码(感谢用户Jay).

I'm trying to accomplish searching for other users only when the user has typed at least 2 words, and only then begin the search in the database (because I don't want to scan the entire database for the users). I had some problems with 2 letter search, but I think I got the code (thanks to user Jay).

但是,当我在模拟器中运行它时,控制台会打印名称,但是在表视图中什么也没显示? (其为空).

However when I run it in the simulator, the console prints name, but nothing shows up in the tableview? (its empty).

你知道我做错了吗?

这是我的代码:

class FollowUsersTableViewController: UIViewController {

    @IBOutlet var tableView: UITableView!

    private var viewIsHiddenObserver: NSKeyValueObservation?
    let searchController = UISearchController(searchResultsController: nil)
    var usersArray = [UserModel]()
    var filteredUsers = [UserModel]()
    var loggedInUser: User?
    //
    var databaseRef = Database.database().reference()
    //usikker på den koden over

    override func viewDidLoad() {

        super.viewDidLoad()

        searchController.searchBar.delegate = self


        //large title
        self.title = "Discover"
        if #available(iOS 11.0, *) {
            self.navigationController?.navigationBar.prefersLargeTitles = true
        } else {
            // Fallback on earlier versions
        }

        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        self.searchController.delegate = self;



        definesPresentationContext = true
        tableView.tableHeaderView = searchController.searchBar



    }

    func searchUsers(text: String) {
        if text.count >= 2 {
            self.usersArray = [] //clear the array each time
            let endingText = text + "\u{f8ff}"
            databaseRef.child("profile").queryOrdered(byChild: "username")
                .queryStarting(atValue: text)
                .queryEnding(atValue: endingText)
                .observeSingleEvent(of: .value, with: { snapshot in

                    for child in snapshot.children {
                        let childSnap = child as! DataSnapshot
                        print(childSnap)
                        let userObj =  Mapper<UserModel>().map(JSONObject: childSnap.value!)
                        userObj?.uid = childSnap.key
                        if childSnap.key != self.loggedInUser?.uid { //ignore this user
                            self.usersArray.append(userObj!)

                        }
                    }
                    self.tableView.reloadData()
                })
        }
    } //may need an else statement here to clear the array when there is no text


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let dest = segue.destination as! UserProfileViewController
        let obj = sender as! UserModel
        let dict = ["uid": obj.uid!, "username": obj.username!, "photoURL": obj.photoURL, "bio": obj.bio]
        dest.selectedUser = dict as [String : Any]
    }





}

// MARK: - tableview methods
extension FollowUsersTableViewController: UITableViewDataSource, UITableViewDelegate {



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchController.searchBar.text!.count >= 2 ? filteredUsers.count : 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FollowTableViewCell

        let user = filteredUsers[indexPath.row]

        cell.title?.text = user.username
        if let url = URL(string: user.photoURL ?? "") {
            cell.userImage?.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "user_male"), options: .progressiveDownload, completed: nil)
            cell.userImage.sd_setIndicatorStyle(.gray)
            cell.userImage.sd_showActivityIndicatorView()
        }

        return cell
    }

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "user", sender: self.filteredUsers[indexPath.row])
    }



}

// MARK: - search methods
extension FollowUsersTableViewController:UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {



    func updateSearchResults(for searchController: UISearchController) {
        searchController.searchResultsController?.view.isHidden = false

        self.searchUsers(text: self.searchController.searchBar.text!)

        filterContent(searchText: self.searchController.searchBar.text!)

        self.tableView.reloadData()
    }

    func filterContent(searchText:String){

        if searchText.count >= 2{


            self.filteredUsers = self.usersArray.filter{ user in
                return(user.username!.lowercased().contains(searchText.lowercased()))
            }
        }
    }


}

推荐答案

您有2个数组usersArrayfilteredUsers

if childSnap.key != self.loggedInUser?.uid { //ignore this user
       self.usersArray.append(userObj!)
}
...
 self.tableView.reloadData()

因此,上述重新加载不会像您一直使用的那样起作用

so the the above reload has no effect as you always use

let user = filteredUsers[indexPath.row]

cellForRowAt中,在这种情况下,您应该使用var

in cellForRowAt , in such cases you should have a var like

var isSearching = false

并在您搜索所有代表&中更改它时dataSource方法

and alter it when you search then in all delegate & dataSource methods

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return isSearching ? filteredUsers.count : usersArray.count
 }
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FollowTableViewCell

    let user = isSearching ? filteredUsers[indexPath.row] : usersArray[indexPath.row] 
  .....
 }

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    isSearching = true
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    isSearching = false
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    isSearching = false
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    isSearching = false
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filteredUsers = usersArray.filter { /* do filter */ }

    if(filteredUsers.count == 0){
        isSearching = false
    } else {
        isSearching = true
    }
    self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "user", sender: isSearching ? self.filteredUsers[indexPath.row] : self.usersArray[indexPath.row])
}

这篇关于为什么我的tableview显示搜索结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆