用户输入时,SearchBar无法正常工作

时间:2015-08-23 15:41:23

标签: ios swift

我有一个带搜索栏的UITableViewController。当用户点击返回按钮时搜索工作,但我无法在用户输入时更新UITable。我已经实现了" searchBardidBeginEditing"功能,但它没有提供任何搜索结果。我将不胜感激任何帮助。

  var findgroups: PFQuery = PFQuery(className: "Groups")



            if self.searchBar.text != "" {
                self.dataparse.removeAllObjects()
                findgroups.whereKey("GroupName", containsString: self.searchBar.text)
                findgroups.findObjectsInBackgroundWithBlock({ (obs: [AnyObject]?, err: NSError?) -> Void in
                    if err == nil && obs != nil {

                        if let obs = obs as? [PFObject] {

                            for objex in obs {

                                self.dataparse.addObject(objex)

                            }

                        }

                    }

                    self.tableView.reloadData()

                })


            } else {



    findgroups.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
        findgroups.orderByDescending("GroupName")
        if error == nil && objects != nil {



            if let objects = objects as? [PFObject] {

                for object in objects {

                    self.dataparse.addObject(object)


                }

            }

        }



        self.tableView.reloadData()
    }


}

}




func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    self.loaddata()

}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()



}






override func viewDidLoad() {
    super.viewDidLoad()
    loaddata()
    searchBar.delegate = self


}


    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    self.dataparse.removeAllObjects()
    searchBar.resignFirstResponder()
    loaddata()
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchBar.text = ""
    searchBar.resignFirstResponder()
    loaddata()
}

1 个答案:

答案 0 :(得分:0)

你的错误就是你打电话给" searchBardidBeginEditing"函数但此函数仅在用户使用UISearchBar搜索时告诉委托。当用户点击栏时,也会调用searchBarSearchButtonClicked函数。因此,您只需调用两次更新函数,而不是每次更改searchText时调用。

要修复它,请在" searchBar(_ searchBar:UISearchBar,textDidChange searchText:String)"中使用数据更新功能。功能如下:

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

    loaddata()
}

你也可以使用searchText并将其提供给loaddata(),因为searchText与self.searchBar.text

相同

以下链接将引导您进入UISearchBarDelegate协议参考,您可以在其中看到协议的每个功能的含义: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UISearchBarDelegate_Protocol/index.html#//apple_ref/occ/intfm/UISearchBarDelegate/searchBar:textDidChange