【发布时间】:2021-10-04 13:33:07
【问题描述】:
我在从 tableview 搜索数据时遇到问题。我想从 tableview 搜索数据,但在搜索时卡住了。下面是我尝试过的代码。我遇到的问题是无法将类型“[Employee]”的值分配给类型“[String]”请帮忙。 TIA
var empList: [Employee]!
var searchedText = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchedText.count
} else {
return empList?.count ?? 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
if searching {
cell.lblTitle.text = searchedText[indexPath.row]
}else {
let resObjects = empList?[indexPath.row]
cell.lblTitle.text = resObjects?.emp_name
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchedText = empList.filter{$0.emp_name?.contains(searchText)}
// The above line gives me error as, cannot assign value of type '[Employee]' to type '[String]'
searching = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
tableView.reloadData()
}
【问题讨论】:
-
var searchedText = [String]()的目标是什么?你想要的是一个被过滤的员工列表,不是吗?所以应该是var filteredEmployees = [Employee](),然后用那个...
标签: ios swift tableview uisearchbar