我已经实现了SearchController
,当我使用SearchController
搜索食物项目时,它返回整个部分。
例如,我将使用Chocolate
搜索SearchController
,它将返回并导致tableView显示整个Sweets
部分,而不仅仅是Chocolate
,它还将返回Lollipops
。我在这做错什么?我对swift很新,任何帮助都会受到赞赏。谢谢。
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
}
}
巴士在线
filteredFood = food.filter { $0.foodList.contains(where: { $0.contains(searchController.searchBar.text!) }) }
实际上你的food
和filteredFood
是一个二维数组。第一个维度是数组本身。第二个 - 内部数组foodList
在Food
对象内。此代码仅过滤此数据结构的外部维度。它说如果有一个字符串匹配foodList
内的搜索,那么整个Food
对象应该通过过滤器。如果这不是你想要的 - 你也必须创建新的Food
对象。可能是这样的:
filteredFood = food.filter { $0.foodList.contains(where: { $0.contains(searchController.searchBar.text!) }) }
.map { Food(foodTaste: $0.foodTaste, foodList: $0.foodList.filter( {$0.contains(searchController.searchBar.text!) }) }