我有一个UISearchBar
,我正在按搜索词过滤UICollectionView
,如下所示:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredRecipes = getRecipes().filter({( recipe : Recipe ) -> Bool in
return recipe.name.lowercased().contains(searchText.lowercased())
})
if searchText == "" || searchText == " " {
filteredRecipes = getRecipes()
}
}
每个Recipe
都有一些属性,我想过滤的其中一个属性是name
,它由几个词组成,例如"红天鹅绒蛋糕"。现在,如果我从以下位置搜索任何内容,该函数将返回此配方:
- 红
- r
- LVET
- 埃德·天鹅绒
我该如何使它根据name
中每个单词的开头过滤食谱。因此,如果我搜索以下内容,它只会返回食谱:
- 红
- 丝绒
- 蛋糕
- 天鹅绒蛋糕
并且如果搜索词什么都没有,或者只是空白,它就会返回所有食谱?
我在这里寻找答案,我只能找到与我现有的解决方案类似的解决方案。谢谢!
使用filter(_:)
、contains(where:)
和hasPrefix(_:)
的组合,如下所示,
filteredRecipes = getRecipes().filter({
let components = $0.name.components(separatedBy: " ")
return components.contains(where: {
$0.lowercased().hasPrefix(searchText.lowercased())
})
})
您可以使用枚举子字符串方法并将recipe.name
的每个单词与searchText
进行比较
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard !searchText.trimmingCharacters(in: .whitespaces).isEmpty else {
filteredRecipes = getRecipes()
return
}
filteredRecipes = getRecipes().filter({
var result = false
$0.name.enumerateSubstrings(in: $0.name.startIndex..<$0.name.endIndex, options: [.byWords], { (word, _, _, _) in
if let word = word, word.caseInsensitiveCompare(searchText) == .orderedSame {
result = true
}
})
return result
})
}