你好我正試圖在我的應用程序中實現一個SearchBar。我遵循一些教程併成功實施了一個SearchBar。但問題是,在我的工作代碼中,數據是硬編碼的,它在NSArray
中,在我的實際應用中,數據來自web服務的NSDictionary
。這是工作代碼。我想實現這個使用的NSDictionarySearchBar在TableView中
class CountryTableViewController: UITableViewController, UISearchResultsUpdating {
var filterTableData = [String]()
var resultSearchController = UISearchController()
var tableData = ["one","two","three"]
override func viewDidLoad() {
super.viewDidLoad()
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.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(self.resultSearchController.active){
return self.filterTableData.count
}else {
return tableData.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CountryTableViewCell
if(self.resultSearchController.active){
cell.countryNameLabel.text = filterTableData[indexPath.row]
return cell
}else{
cell.countryNameLabel.text = tableData[indexPath.row]
return cell
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterTableData.removeAll(keepCapacity: false)
let searchPredict = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredict)
filterTableData = array as! [String]
self.tableView.reloadData()
}
}
我NSDictionary的數據是這樣的
{
0 = {
City = {
code = 11859;
"country_id" = 177;
"created_at" = "<null>";
id = 23219;
name = Lahore;
};
Country = {
id = 177;
name = "Pakistan
\n";
};
State = {
Country = (
);
id = 3262;
name = "Punjab
";
};
};
code = 200;
}
我一直在使用NSDictionary的嘗試,但沒有成功
在搜索哪個標籤是你填充它的名字? –
@ReshmiMajumder是城市和國家的名字..這是否回答你的問題? – hellosheikh