【发布时间】:2015-02-02 18:23:33
【问题描述】:
我正在快速构建一个应用程序,需要能够搜索城市,我希望搜索能够使用自动完成功能。
所以我首先在 xib 中创建了一个视图控制器,其中包含一个 UISearch 栏及其关联的控制器。我为视图控制器编写的类如下:
import UIKit
class LocationViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate {
// MARK: - Properties
var dirty: Bool = false
var loading: Bool = false
var suggestions: Array<String> = [] {
didSet {
searchDisplayController?.searchResultsTableView.reloadData()
}
}
// MARK: - Initialization
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
searchDisplayController?.searchBar.placeholder = "Ville ou adresse"
}
// MARK: - UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if countElements(searchText) > 0 {
if (loading) {
dirty = true
} else {
loadSearchSuggestions()
}
}
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
suggestions = []
}
// MARK: - Search backend
func loadSearchSuggestions() {
loading = true
var query = searchDisplayController?.searchBar.text
var urlEncode = query!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
var urlString = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=MYAPIKEY&components=country:FR&input=\(urlEncode)"
var request = NSURLRequest(URL: NSURL(string: urlString)!)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if (error != nil) {
self.loading = false
println(error.localizedDescription)
return
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &err) as Dictionary<String,AnyObject>
var predictions = jsonResult["predictions"] as Array<AnyObject>
var currentSug: Array<String> = []
for prediction in predictions {
var predDict = prediction as Dictionary<String, AnyObject>
var adress = predDict["description"] as String
currentSug.append(adress)
}
if err != nil {
println("JSON Error in search \(err!.localizedDescription)")
return
}
self.suggestions = currentSug
if self.dirty {
self.dirty = false
self.loadSearchSuggestions()
}
self.loading = false
})
task.resume()
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "suggestCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
}
if suggestions.count > 0 {
cell!.textLabel!.text = suggestions[indexPath.row]
}
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return suggestions.count
}
}
在某一点之前一切正常。当我在搜索框中写信时,请求有效,我得到的结果存储在我的建议变量中。
唯一的问题是:包含结果的表视图没有按应有的方式重新加载(如建议 var 中的 didSet 中指定的那样)。除非我尝试滚动空列表。
现在,如果我键入第二个字符,我的表格视图会显示仅键入一个字符时的结果。如果我尝试滚动,那么我会得到正确的结果。
非常感谢您花时间回答我的问题。我可能在我的代码中犯了错误,因为我对 swift 和一般编程仍然很陌生。
【问题讨论】:
-
我看不到你在哪里打电话
tableView.reloadData()。 -
在建议数组的 didSet 中。因此,每次更新数组时,它都应该重新加载表 var 建议: Array
= [] { didSet { searchDisplayController?.searchResultsTableView.reloadData() } }
标签: ios swift autocomplete ios8 uisearchbar