Filter Array with UISearchBar

隐身守侯 提交于 2019-12-06 15:27:41

问题


I am currently using the following code to filter the array and present the results in my tableView. The problem is that this only returns results if the search matches the exact word. How do I change my array filter to search each character as I type it?

let data = ["Mango", "Grape", "Berry", "Orange", "Apple"]

var filteredData: [String] = []

filteredData = data.filter({$0 == searchBar.text})

The only way to get "Mango" to show up in my tableView, I have to type Mango in the search bar, typing "Man" doesn't show any results.


回答1:


Try this:

filteredData  = data.filter { $0.contains(_ other: searchBar.text) }



回答2:


Swift 5 Solution:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    filteredData = data

    if searchText.isEmpty == false {
        filteredData = data.filter({ $0.contains(searchText) })
    }

    tableView.reloadData()
}

This ensures that when the searchBar is empty, it goes back to displaying all your array's data, while also reloading the tableView every time you change the text.




回答3:


This will surely help you out:

var filteredData: [String] = []

 func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String){
    filterContentForSearchText(searchText: searchText)
}

func filterContentForSearchText(searchText: String, scope: String = "All") {
    if searchText != "" {

        filterData = data.filter {name in

                                return   name.lowercased().contains(searchText.lowercased())

        }
    }else { self.filterData = self.data}
}


来源:https://stackoverflow.com/questions/45473183/filter-array-with-uisearchbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!