我正在使用一个名为 sections 的数组变量,因为 TableView 具有可折叠的部分:
var sections = [
// TESTING CODE FOR SECTIONS
Section(sec: "One",
subSec: ["A", "B", "C", "D", "E"],
expanded: false),
Section(sec: "Two",
subSec: ["A", "B", "C", "D", "E"],
expanded: false),
Section(sec: "Three",
subSec: ["A", "B", "C", "D", "E"],
expanded: false),
我正在尝试使用 UISearchController 使 TableView 可搜索。到目前为止,这是我尝试过的方法,但它不起作用:
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filtered = sections.filter({( section : Section) -> Bool in
return section.subSec.name.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
我了解该函数的工作原理,但似乎无法让它与变量中的 subSec 一起工作。
//SEARCH
var filteredSections: [String]?
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
//SEARCH
filteredSections = sections
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
}
我收到诸如“无法将类型“[Section]”的值分配给类型“[String]”之类的错误?我明白为什么,但我不知道如何解决这个问题。
部分定义:
struct Section {
var sec: String!
var subSec: [String]! // [ ] = Array of Strings
var expanded: Bool!
init(sec: String, subSec: [String], expanded: Bool) {
self.sec = sec
self.subSec = subSec
self.expanded = expanded
}
}
最佳答案
filteredSections
是一个字符串数组,您正在尝试分配在 Section
数组上调用的过滤器函数的输出,它返回一个 数组>Section
,所以显然不行。
如果要返回String
作为过滤Section
数组的结果,需要结合使用filter
和 >map
,这可以通过单个 flatMap
完成。
flatMap 中的三元运算符检查与过滤器相同的条件,但如果条件计算结果为真,则返回 section.subSec.name
,否则返回 nil
, flatMap
会简单地忽略它,因此输出数组将只包含匹配的子部分名称。
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filtered = sections.flatMap{ return $0.subSec.name.lowercased().contains(searchText.lowercased()) ? searchText : nil }
tableView.reloadData()
}
因为你没有在你的代码中包含 Section
的定义,我无法测试这个函数,但是如果 subSec.name
是一个 String
,它将正常工作。
关于swift - UISearchBar 不适用于数组中的子部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45894059/