Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift SearchController-我不希望在用户尚未开始键入时显示数据_Swift_Xcode_Firebase - Fatal编程技术网

Swift SearchController-我不希望在用户尚未开始键入时显示数据

Swift SearchController-我不希望在用户尚未开始键入时显示数据,swift,xcode,firebase,Swift,Xcode,Firebase,]我在我的应用程序中构建了一个SearchViewController,它只搜索用户 一切都很好,除了当我进入viewcontroller时,它会在我开始搜索之前显示firebase数据库中的每个用户?我希望在输入至少两个字母之前,tableview不会显示结果。有人知道我可以实现这个吗 这是我的密码: class FollowUsersTableViewController: UITableViewController ,UISearchResultsUpdating, UISearchCon

]我在我的应用程序中构建了一个SearchViewController,它只搜索用户

一切都很好,除了当我进入viewcontroller时,它会在我开始搜索之前显示firebase数据库中的每个用户?我希望在输入至少两个字母之前,tableview不会显示结果。有人知道我可以实现这个吗

这是我的密码:

class FollowUsersTableViewController: UITableViewController ,UISearchResultsUpdating, UISearchControllerDelegate{

//    @IBOutlet var followUsersTableView: UITableView!

func updateSearchResults(for searchController: UISearchController) {
    searchController.searchResultsController?.view.isHidden = false
    filterContent(searchText: self.searchController.searchBar.text!)
    self.tableView.reloadData()
}
private var viewIsHiddenObserver: NSKeyValueObservation?
let searchController = UISearchController(searchResultsController: nil)
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
var loggedInUser: User?

var databaseRef = Database.database().reference()

override func viewDidLoad() {
    super.viewDidLoad()
    //large title
    self.title = "Discover"
    if #available(iOS 11.0, *) {
        self.navigationController?.navigationBar.prefersLargeTitles = true
    } else {
        // Fallback on earlier versions
    }
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    self.searchController.delegate = self;
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar

    databaseRef.child("profile").queryOrdered(byChild: "username").observe(.childAdded, with: { (snapshot) in

        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary
        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedInUser?.uid) {
            print("Same as logged in user, so don't show!")
        } else {
            self.usersArray.append(snapshot)
            //insert the rows
            self.tableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
            self.tableView.reloadData()
        } 
    }) { (error) in
        print(error.localizedDescription)
    }

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if searchController.isActive && searchController.searchBar.text != ""{
        return filteredUsers.count
    }

    return self.usersArray.count
}

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

    let user : NSDictionary?

    if searchController.isActive && searchController.searchBar.text != ""{
        user = filteredUsers[indexPath.row]
    }
    else
    {
        user = self.usersArray[indexPath.row]
    }

    cell.title?.text = user?["username"] as? String
    let url = URL(string: user?["photoURL"] as! String)!
    cell.userImage?.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "user_male"), options: .progressiveDownload, completed: nil)
    return cell
}

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

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let arr = self.searchController.isActive ? self.filteredUsers : self.usersArray
    self.performSegue(withIdentifier: "user", sender: arr[indexPath.row])
}

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

func filterContent(searchText:String)
{
    if searchText != ""{
        self.filteredUsers = self.usersArray.filter{ user in

            let username = user!["username"] as? String

            return(username?.lowercased().contains(searchText.lowercased()))! 
        }
    }
}
那么,有没有人能给我一些建议,告诉我如何才能做到这一点?

在您的numberOfRowsInSection中,您将返回self.usersArray.count。如果不想显示所有结果,只需返回0,就不会显示任何结果

如果要在输入至少2个字符时显示搜索,请使用searchBar.text的count属性

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if searchController.isActive && searchController.searchBar.text != "" && searchController.searchBar.text.count >= 2 {
        return filteredUsers.count
    }

    return 0

}
在原始代码中:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if searchController.isActive && searchController.searchBar.text != ""{
        return filteredUsers.count
    }


    return self.usersArray.count

}
您返回的是
self.userArray.count
,这可能解释了为什么它在开始时显示整个未过滤的数组,而不向搜索栏中输入任何文本

我还注意到,
filterContent(searchText:String)
函数尚未在代码中调用

但是我认为当您还不想更改结果表时,
返回self.usersArray.count
行作为默认返回值是可以的,因为当表为空时,当已经输入了1或2个字母时,它可能会对用户产生影响

而且

在代码的另一部分:

self.tableView.insertRows(位于:[indepath(行:self.usersArray.count-1,节:0)],带有:UITableViewRowAnimation.automatic)


我认为当使用
insertRow
时,不再需要
self.tableView.reloadData()
。您好,如果我添加了return 0(其中我返回self.usersArray.count),我会得到以下错误:libc++abi.dylib:以NSException(lldb)类型的未捕获异常终止。如果您不想返回任何单元格,则返回0是一个好办法。看起来您还需要检查cellForRow方法中的字符计数。您还可以在viewDidLoad中插入行。如果您只想显示过滤后的字符,是否需要执行此操作?您好,我还没有添加字符计数,我只是在numberOfRowsInSection中添加了“返回0”,如您上面所述。但这给了我一个错误。。我只想显示filteredUsers,而不是usersArray,因为我只想在用户开始键入时显示用户我想我需要usersArray使用“filteredUsers”进行筛选,对吗?是的,但我同意我应该返回0。但是当我这样做的时候,我得到了一个错误?@MattGilbert有点推论,但是
numberofrowsinssection
函数是一个
UITableViewDataSource
函数。由于
FollowUsersTableViewController
不是
UITableViewDataSource
的子类,因此您没有真正重写任何内容,因此必须将
FollowUsersTableViewController
设为
UITableViewDataSource
的子类,然后将self指定为表的数据源。FollowUsersTableViewController类继承自UITableViewController,默认情况下,它应符合UITableViewDataSource和UITableViewDelegate。但当我返回0时,我还是得到了错误?@MattGilbert你是对的,我错了!