2016-01-22 64 views
0

你好我一直在看視頻來做這個代碼,但沒有任何工作我試圖圍繞代碼玩,仍然沒有得到什麼錯。問題是我沒有任何錯誤,當我運行代碼時,它不會在tableView中顯示結果。我想要做的是我想在解析用戶列表中搜索。 下面的代碼:快速使用搜索欄解析

func searchBarSearchButtonClicked(searchBar: UISearchBar){ 
    searchBar.resignFirstResponder() 
    print("search word =\(searchBar.text)") 

    let usernameQuery = PFQuery(className: "User") 
    usernameQuery.whereKey("username", containsString: searchBar.text) 

    usernameQuery.findObjectsInBackgroundWithBlock { 
     (results: [PFObject]?, error: NSError?) -> Void in 

     if error != nil { 
      let myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle:UIAlertControllerStyle.Alert) 

      let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) 

      myAlert.addAction(okAction) 

      self.presentViewController(myAlert, animated: true, completion: nil) 

      return 
     } 
     if let objects = results! as? [PFObject]{ 
      self.searchResults.removeAll(keepCapacity: false) 

      for object in objects{ 
       let usernameid = object.objectForKey("username") as! String 
       self.searchResults.append(usernameid) 
      } 
      dispatch_async(dispatch_get_main_queue()){ 
       self.myTable.reloadData() 
       self.mySearchBar.resignFirstResponder() 
      } 
     } 
    } 

}

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

    myCell.textLabel?.text = searchResults[indexPath.row] 

    return myCell 
} 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ 
    mySearchBar.resignFirstResponder() 
} 

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


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

    return searchResults.count 
} 

}

+0

什麼不完全正常工作?你嘗試調試它嗎? – Ammo

+0

當我使用搜索欄時,它不會在tableveiew中顯示結果 –

回答

0

TL; DR

你是不是從UISearchBar展開搜索字符串。

詳細

Apple's official documentation for UISearchBar看,則可以看出,text屬性類型String?的。

當期待通過這方面的知識你的代碼,然後將下面的行看起來有點suspecious因爲你沒有進行任何形式的解包:

usernameQuery.whereKey("username", containsString: searchBar.text) 

這甚至可以進一步用一個簡單的遊樂場測試進行研究:

import UIKit 

let searchBar = UISearchBar() 
searchBar.text = "Kumuluzz" 
let output = searchBar.text 
print("Output: \(output)") 

輸出在這個遊樂場(在右側欄所示)如下:

"Output: Optional("Kumuluzz")\n" 

這意味着我的用戶名必須是Optional("Kumuluzz")才能匹配您在User基地的查詢。

所以最後,在text屬性上應用某種解包。

+0

如果我對您的問題的回答有幫助並且正在實現,請接受它作爲您的帖子的答案,以向其他用戶指出您的問題已得到解決:) http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Kumuluzz