我有一个搜索栏,可以过滤菜谱标题的xml数组。问题是我必须搜索整个标题,否则我看不到建议的结果。例如,如果我有“全麦华夫饼”和“全麦面包”,输入“and”不会返回任何东西。输入“全麦华夫饼”返回成功。这是searchBar函数
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
myTableView.reloadData()
} else {
isSearching = true
filteredData = tableViewDataSource.filter({$0.title == searchBar.text})
myTableView.reloadData()
}
}我非常确定解决方案与区分大小写以及在设置filteredData时返回某些字符有关。提前感谢您的帮助
发布于 2018-04-20 04:25:50
如果要搜索以搜索文本开头的字符串,可以使用contains过滤数组中包含文本的任何项,也可以使用hasPrefix。
就像这样,
filteredData = tableViewDataSource.filter { $0.title.contains(searchBar.text) ?? "" }或,
filteredData = tableViewDataSource.filter { $0.title.hasPrefix(searchBar.text) ?? "" }发布于 2018-04-20 05:06:33
在我的情况下,使用range是可行的
filteredData = tableViewDataSource.filter({$0.title.range(of: searchBar.text!) != nil})https://stackoverflow.com/questions/49929584
复制相似问题