【发布时间】:2016-05-21 13:26:20
【问题描述】:
我在我的 tableview 应用程序中实现了一个搜索功能。唯一的问题是当我点击搜索栏,然后点击取消时,之前显示的单元格消失了。这是所有库存;什么也没有变。当我添加搜索显示控制器时,我从情节提要中添加了它,没有进行任何配置。
import UIKit
class DataTableExercisesTableViewController: UITableViewController, UISearchResultsUpdating {
let exercises = ["Abs", "Arms", "Back", "Chest", "Legs", "Shoulders", "Triceps"]
var filteredTableData = [String]()
var resultSearchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
resultSearchController.searchResultsUpdater = self
resultSearchController.dimsBackgroundDuringPresentation = false
resultSearchController.searchBar.sizeToFit()
resultSearchController.hidesNavigationBarDuringPresentation = false
tableView.tableHeaderView = resultSearchController.searchBar
return controller
})()
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.active {
return filteredTableData.count
} else {
return exercises.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ExerciseCell", forIndexPath: indexPath)
// Configure the cell...
if (self.resultSearchController.active) {
cell.textLabel?.text = filteredTableData[indexPath.row]
return cell
}
else {
cell.textLabel?.text = exercises[indexPath.row]
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (exercises as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
【问题讨论】:
-
您的代码中某处存在错误。发布显示/隐藏搜索栏的代码以及过滤数据的代码。
-
@DuncanC 就是这样。没有设置代码。我刚刚从情节提要的对象库中将它添加到我的 tableview 中。您是否推荐任何资源来学习如何设置它?
-
shrikar.com/…点击此链接
-
你的代码一定有bug。请发布您的代码。
-
@DuncanC 在这里我用我的代码更新了问题。
标签: ios swift uitableview tableview uisearchdisplaycontroller