我正在尝试在我的应用程序中提供搜索功能。搜索基本上会在后端的 Parse 类中搜索用户输入。
到目前为止,下面的代码非常适合我的情况,除了 View 加载后(在开始输入任何内容之前),它会加载表行中后端的所有用户名。当用户输入字母时,它会进行过滤。我希望拥有所有相同的功能,除了在 View 加载后立即显示表行中的所有用户。如何实现这一目标?
class FriendByUsernameTableViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
var friendObject = FriendClass()
@IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var data:[PFObject]!
var filtered:[PFObject]!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
search()
}
func search(searchText: String? = nil){
let query = PFQuery(className: "_User")
if(searchText != nil){
query.whereKey("appUsername", containsString: searchText)
}
query.findObjectsInBackgroundWithBlock { (results, error) -> Void in
self.data = results as? [PFObject]!
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(self.data != nil){
return self.data.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
let obj = self.data[indexPath.row]
cell.textLabel!.text = obj["appUsername"] as? String
return cell
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
search(searchText)
}
}
代码基于本教程:http://shrikar.com/parse-search-in-ios-8-with-swift/
最佳答案
尝试添加
if searchText!.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()) != "" {
query.findObjectsInBackgroundWithBlock()
}
当然,在您的搜索功能中以及 block 中。
这样,如果您点击搜索栏或点击一堆空格,您就不会进行查询。
此外,如果您不希望在加载时显示用户,请不要在 viewDidLoad()
中调用 search()
关于ios - Swift - 搜索栏初始加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777777/