如何将UISearchBarController与数组子节一起使用 [英] How to use UISearchBarController with array subsection
问题描述
我正在使用以下数组结构来创建带有部分的tableView
I am using the following array structure to create a tableView with sections
struct words {
var sectionName : String!
var coptic : [String]!
var english : [String]!
}
var array = [words]()
var filtered = [words]()
array = [words(sectionName: "", coptic: [""], English: [""])]
我想使用一个与此类似的代码的搜索控制器
I want to utilize a searchcontroller using similar code to this
func updateSearchResults(for searchController: UISearchController) {
// If we haven't typed anything into the search bar then do not filter the results
if searchController.searchBar.text! == "" {
filtered = array
} else {
// Filter the results
filtered = array.filter { $0.coptic.lowercased().contains(searchController.searchBar.text!.lowercased()) }
}
不幸的是,由于coptic是一个[String],而不仅仅是一个String,因此该代码无法正常工作.有没有一种方法可以对此进行修改,以便能够过滤对coptic子节的搜索?
Unfortunately, because coptic is a [String], and not simply a String, the code doesn't work. Is there a way to modify this to be able to filter a search for the coptic subsection?
推荐答案
您可以这样做.
func updateSearchResults(for searchController: UISearchController) {
// If we haven't typed anything into the search bar then do not filter the results
if searchController.searchBar.text! == ""
{
filtered = array
}
else
{
filtered.removeAll()
array.forEach({ (word:words) in
var tempWord:words = words.init(sectionName: word.sectionName, coptic: [""], english: [""])
let copticArray = word.coptic.filter({ (subItem:String) -> Bool in
let a = subItem.lowercased().contains(searchController.searchBar.text!.lowercased())
return a;
})
tempWord.coptic = copticArray
filtered.append(tempWord)
})
}
}
输入array = array = [words(sectionName:"abc",coptic:["apple","ball","cat","dog"],英语:["])]
Input array = array = [words(sectionName: "abc", coptic: ["apple","ball","cat","dog"], english: [""])]
搜索应用"
输出单词(sectionName:abc,coptic:["apple"],英语:["]))
OUTPUT words(sectionName: abc, coptic: ["apple"], english: [""])]
这篇关于如何将UISearchBarController与数组子节一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!