我正在尝试让此搜索栏显示属于tableview中标题的图像。问题是它在搜索时始终显示数组中的第一个图像。我如何获得相应图像的索引?
let tableData = ["One","Two","Three"]
let imageArray = ["indianFood.jpg", "thaiFood.jpg", "chineseFood.jpg"]
var filteredTableData = [String]()
var resultSearchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
resultSearchController.searchResultsUpdater = self
resultSearchController.dimsBackgroundDuringPresentation = false
resultSearchController.searchBar.sizeToFit()
resultSearchController.hidesNavigationBarDuringPresentation = false
tableView.tableHeaderView = resultSearchController.searchBar
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if (self.resultSearchController.active) {
return self.filteredTableData.count
}
else {
return self.tableData.count
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// 3
if (self.resultSearchController.active) {
cell.textLabel?.text = filteredTableData[indexPath.section]
}
else {
let image = UIImage(named: imageArray[indexPath.section])
cell.imageView?.image = image
cell.textLabel?.text = tableData[indexPath.section]
}
return cell
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}