Swift Tableview搜索结果单元格单击以选中标记不显示

时间:2019-11-07 10:34:38

标签: ios swift uitableview searchbar

对于我来说,我是在JSON的帮助下将codable数据加载到UITableView中。在这里,我实现了Tableview多个单元格checkmark选项。现在,我有两个数组filteredDatamembersData。如果我单击对勾标记,则不进行搜索,但是如果我单击对勾标记,则搜索结果不显示。同样,选择后需要将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)
    }

1 个答案:

答案 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)
}