如何在Swift中为多个字符串过滤UISearchBar?

时间:2016-04-03 22:08:47

标签: swift

我有一组struct' s,每个都有标题和副标题:

struct searchItem {
    var title: String
    var subtitle: String
}

let itemArray: [searchItem] = [
        searchItem(title: "Bob", subtitle: "Man"),
        searchItem(title: "Susan", subtitle: "Woman"),
        searchItem(title: "Joe", subtitle: "Man")
]

var filteredArray = [searchItem]()

每个searchItem titlesubtitle用于在tableViewCell中创建tableViewControllerUISearchBar在顶部:

simulator image of tableView

我需要以某种方式根据搜索字词和itemArray searchItem titlesubtitle来过滤{{1}},所以搜索字词和#34; Man"或者#34; Bob"将返回个人鲍勃。

如何做到这一点?提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用filter swift数组方法过滤数组。当您使用过滤器时,返回其他数组项目取决于您的 searchText 。因此,您应该将搜索到的项目添加到新的filteredArray重新加载您的tableView

if let searchBarText = searchController.searchBar.text{
            let searchText = searchBarText.lowercaseString
            filteredArray = self. itemArray.filter({$0.title.lowercaseString.rangeOfString(searchText) != nil})
            filteredArray += self.itemArray.filter({$0. subtitle.lowercaseString.rangeOfString(searchText) != nil})
            tableView.reloadData()
}

答案 1 :(得分:1)

Swift 3版本:

if let searchBarText = searchController.searchBar.text{
            let searchText = searchBarText.lowercaseString
            filteredArray = categoryArray.filter ({$0.title.lowercased().range(of: searchText.lowercased()) != nil})
            filteredArray += categoryArray.filter ({$0.sybtitle.lowercased().range(of: searchText.lowercased()) != nil})
            tableView.reloadData()
}