我在我的tableview應用程序中實現了一個搜索功能。唯一的問題是當我點擊搜索欄,然後點擊取消,先前顯示的單元格消失。這是全部股票;什麼也沒有變。當我添加搜索顯示控制器時,我從故事板中添加了它,但沒有配置。當搜索欄被點擊時,Tableviewcells消失 - Swift
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中。你是否推薦任何資源來學習如何設置它? –
http://shrikar.com/swift-ios-tutorial-uisearchbar-and-uisearchbardelegate/點擊此鏈接 – karthik