你好我正试图在我的应用程序中实现一个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