对于我来说,我是在JSON
的帮助下将codable
数据加载到UITableView中。在这里,我实现了Tableview多个单元格checkmark
选项。现在,我有两个数组filteredData
和membersData
。如果我单击对勾标记,则不进行搜索,但是如果我单击对勾标记,则搜索结果不显示。同样,选择后需要将filterdata结果中的值保存到主数据源。该如何解决?
我的Tableview代表
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searching ? filteredData.count : membersData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TeamlistCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TeamlistCustomCell
let textForRow = searching ? filteredData[indexPath.row] : membersData[indexPath.row]
cell.name.text = textForRow.firstname
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
membersData[indexPath.row].isSelected.toggle()
tableView.reloadRows(at: [indexPath], with: .none)
let selectedAreas = membersData.filter{$0.isSelected}
}
SearchBar TextDidChange
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if !searchText.isEmpty {
filteredData = membersData.filter({ ($0.firstname?.localizedCaseInsensitiveContains(searchText))! })
searching = true
} else {
filteredData.removeAll()
searching = false
}
tableView.reloadData()
}
存储选定的值CheckMark
func saveSelection() {
let selectedAreaNames = membersData.filter{$0.isSelected}.map{$0.userid}
UserDefaults.standard.set(selectedAreaNames, forKey: "selectedNames")
let selectedData = membersData.filter{$0.isSelected}
UserDefaults.standard.set(try? PropertyListEncoder().encode(selectedData), forKey:"session data")
delegate?.pass(data: selectedData) //call the func in the previous vc
self.dismiss(animated: true, completion: nil)
}
答案 0 :(得分:0)
完整代码
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
if searching == false {
membersData[indexPath.row].isSelected.toggle()
} else {
filteredData[indexPath.row].isSelected.toggle()
}
tableView.reloadRows(at: [indexPath], with: .none)
}