Ich habe eine SearchController
implementiert, und wenn ich das Nahrungsmittel mit der SearchController
suche, wird der gesamte Abschnitt zurückgegeben.UISearchController gibt den Abschnitt anstelle des gefilterten Tabellenansichtsobjekts zurück
Zum Beispiel werde ich suchen Chocolate
die SearchController
verwenden und es würde zurückkehren und führen in der Tableview Anzeige den gesamten Abschnitt von Sweets
, statt nur Chocolate
, wird es Lollipops
auch zurück. Was mache ich hier falsch? Ich bin ziemlich neu zu schnell, jede Hilfe würde geschätzt werden. Vielen Dank.
struct Food {
let foodTaste: String
let foodList: [String]
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
if searchController.searchBar.text! == "" {
filteredFood = food
} else {
filteredFood = food.filter { $0.foodList.contains(where: { $0.contains(searchController.searchBar.text!) }) }
self.tableView.reloadData()
}
}
var tableView = UITableView()
var food = [Food]()
var filteredFood = [Food]()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
filteredFood = food
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
definesPresentationContext = true
tableView.frame = self.view.frame
self.view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
let sweets = Food(foodTaste: "Sweet", foodList: ["Chocolate",
"Lollipops"])
let sour = Food(foodTaste: "Sour", foodList: ["Lemon", "Limes"])
food.append(sweets)
food.append(sour)
}
func numberOfSections(in tableView: UITableView) -> Int {
return filteredFood.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredFood[section].foodList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = filteredFood[indexPath.section].foodList[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return filteredFood[section].foodTaste
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 4
}
}
danke, das hat funktioniert! – Mau