搜索结果问题 - Xcode项目

时间:2016-04-30 07:40:40

标签: ios uitableview search firebase

我正在使用swift和firebase开发iOS应用程序:

我尝试将搜索栏添加到表格视图中,如下代码所示:

import UIKit

class MyTableVC: UITableViewController,UISearchResultsUpdating  {

var resultSearchController = UISearchController(searchResultsController: nil)
//var filteredUsers = [nsdi]()

var filteredUsers: NSMutableArray = []
var UserNamesArray: NSMutableArray = []


override func viewDidLoad() {
    super.viewDidLoad()

//        self.resultSearchController = UISearchController(searchResultsController: nil)
//        self.resultSearchController.searchResultsUpdater = self
//        self.resultSearchController.dimsBackgroundDuringPresentation = false
//        //self.resultSearchController.searchBar.sizeThatFits()


    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    })()


    self.tableView.tableHeaderView = self.resultSearchController.searchBar

    self.tableView.reloadData()


    let ref = Firebase(url: "https://hissah-1st-fb-test.firebaseio.com/Users")

    ref.queryOrderedByChild("Job").queryEqualToValue("Programs")
        .observeEventType(.Value, withBlock: { snapshot in

            if let dict = snapshot.value as? NSMutableDictionary{
                //print("dict====== \(dict)")

                for (key,value) in dict {
                    let mainDict = NSMutableDictionary()
                    mainDict.setObject(key, forKey: "userid")

                    if let dictnew = value as? NSMutableDictionary{

                        if let metname = dictnew["UserName"] as? String
                        {
                            mainDict.setObject(metname, forKey: "UserName")
                        }
                        if let metname = dictnew["Details"] as? String
                        {
                            mainDict.setObject(metname, forKey: "Details")
                        }
                        if let metname = dictnew["Email"] as? String
                        {
                            mainDict.setObject(metname, forKey: "Email")
                        }
                    }

                    //print("mainDict========= \(mainDict)")

                    self.UserNamesArray.addObject(mainDict)

                }
                //print("UserNamesArray ==== \(self.UserNamesArray)")
            }
            self.tableView.reloadData()

        })
}





// MARK: - Table view data source

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   if self.resultSearchController.active
   {
    return self.filteredUsers.count
    }else
   {
    return UserNamesArray.count
    }
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell

    if self.resultSearchController.active
    {
       // cell.textLabel?.text = self.filteredUsers[indexPath.row] as? String


        if let name = self.filteredUsers[indexPath.row] as? NSMutableDictionary{

            cell.textLabel?.text = name["UserName"] as? String
            cell.detailTextLabel?.text = name["Details"] as? String
        }


    }
    else{


    if let name = UserNamesArray[indexPath.row] as? NSMutableDictionary{

        cell.textLabel?.text = name["UserName"] as? String
        cell.detailTextLabel?.text = name["Details"] as? String
    }
    }
    cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    dispatch_async(dispatch_get_main_queue()) { [unowned self] in
        let detailsViewController = self.storyboard!.instantiateViewControllerWithIdentifier("DetailsViewController") as! DetailsVC

        if let name = self.UserNamesArray[indexPath.row] as? NSMutableDictionary{

            detailsViewController.self.strUserid = name["userid"] as? String
        }
        self.navigationController?.pushViewController(detailsViewController, animated: true)
    }
}

func updateSearchResultsForSearchController(searchController: UISearchController)
{
    filteredUsers.removeAllObjects()

    //attributeA contains[cd] $A OR attributeB contains[cd]
    let searchPredicate = NSPredicate(format: "UserName contains[cd] %@ OR Details contains[cd] %@", searchController.searchBar.text!,searchController.searchBar.text!)
    let array = (UserNamesArray as NSArray).filteredArrayUsingPredicate(searchPredicate)
    for type in array {
        // Do something

        filteredUsers .addObject(type)
    }

   // filteredUsers = array as! [String]

    self.tableView.reloadData()
}



 }

这是表格视图: enter image description here

当用户点击任何项目时,它会从firebase中检索该项目的信息,如果我点击Sara,它会在此处显示她的姓名和电子邮件: enter image description here

当我搜索mariah或hello的例子时,它会给出正确的结果,如下所示: enter image description here

但如果我点击结果项目,它总是会检索第一个项目的信息!'Sara的信息',例如结果mariah,给出: enter image description here

任何人都可以告诉我,我该如何解决这个问题?为什么会这样?

2 个答案:

答案 0 :(得分:1)

cellForRow中,您正在检查用户是否正在积极搜索并过滤结果

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if self.resultSearchController.active
    {


        if let name = self.filteredUsers[indexPath.row] as? NSMutableDictionary{
        // other code
    }
    else{
      ..// here get data from original array

    if let name = UserNamesArray[indexPath.row] as? NSMutableDictionary{


    return cell
}
  

然而,在didSelectRow方法中,您没有使用相同的流程

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


   if let name = self.UserNamesArray[indexPath.row] as? NSMutableDictionary{

这就是你得到错误结果的原因。 你还需要检查searchController是否在这里活动

    if self.resultSearchController.active
    {
       //get from filteredUsers
    }
    else{ 
       //get from original users
    }

答案 1 :(得分:1)

我发现您没有在didSelectRowAtIndexPath设置搜索结果的返回数组。所以你设置didSelectRowAtIndexPath代码如下:

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


        if self.resultSearchController.active
        {

            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            dispatch_async(dispatch_get_main_queue()) { [unowned self] in
                let detailsViewController = self.storyboard!.instantiateViewControllerWithIdentifier("DetailsViewControllerroller") as! DetailsViewController

                if let name = self.filteredUsers[indexPath.row] as? NSMutableDictionary{

                    detailsViewController.self.strUserid = name["userid"] as? String
                }

                self.navigationController?.pushViewController(detailsViewController, animated: true)

            }

        }
        else
        {
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            dispatch_async(dispatch_get_main_queue()) { [unowned self] in
                let detailsViewController = self.storyboard!.instantiateViewControllerWithIdentifier("DetailsViewControllerroller") as! DetailsViewController

                if let name = self.UserNamesArray[indexPath.row] as? NSMutableDictionary{

                    detailsViewController.self.strUserid = name["userid"] as? String
                }

                self.navigationController?.pushViewController(detailsViewController, animated: true)

            }


        }