我有一个搜索栏,它可以过滤食谱标题的xml数组。问题是我必须搜索整个标题,否则我看不到建议的结果。例如,如果我有“全麦华夫饼”和“全麦面包”,键入“Whole”将不返回任何内容。输入“全麦华夫饼”成功返回。这是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时返回某些字符。提前谢谢你的帮助

最佳答案

如果要搜索以搜索文本开头的字符串,可以使用contains筛选数组中包含文本的任何项,也可以使用hasPrefix
像这样的东西,

filteredData  = tableViewDataSource.filter { $0.title.contains(searchBar.text) ?? "" }

或者,
filteredData = tableViewDataSource.filter { $0.title.hasPrefix(searchBar.text) ?? "" }

07-25 21:22
查看更多