[英]Swift Tableview search result selected cell checkmark not persisting
[英]Swift Tableview search result cell click to checkmark not showing
在我的例子中,我在codable
的帮助下加载JSON
数据。 在这里,我实现了 Tableview 多单元格复选checkmark
选项。 现在,我有两个数组filteredData
和membersData
。 如果我单击复选标记工作但没有搜索,但如果我单击复选标记不显示搜索结果后。 此外,选择后需要将过滤数据结果中的值保存到主数据源。 如何解决这个问题?
我的 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}
}
搜索栏 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()
}
存储选定的值复选标记
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)
}
完整代码
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.