重新加载表视图时如何保存用户选择?

时间:2017-09-26 11:09:07

标签: ios uitableview swift3

我有一个表格视图,显示所选项目的复选标记。当我转到上一个视图控制器然后重新加载我的表视图控制器时,之前选择的选定项目应该已经有了复选标记。我试过但它只启用了最后一个选定的项目。任何人都可以帮我实现这个吗?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "filterSelectionCell", for: indexPath) as! FilterSelectionCell
        activityIndicator.stopAnimating()
        activityIndicator.hidesWhenStopped = true
        tableDetails.isHidden = false
        let product = products[indexPath.row]
        cell.brandProductName.text = product.name
        cell.accessoryType = product.selected ? .checkmark : .none
        if namesArray.count != 0 {
            for name in namesArray{
                if product.name.contains(name){
                        print(product.name)
                    cell.accessoryType = .checkmark
                    }
                    else {
                        cell.accessoryType = .none
                    }
                }
                }
        return cell
    }
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selected = products[indexPath.row].selected
        products[indexPath.row].selected = !selected
        tableView.reloadRows(at: [indexPath], with: .none)
        let selectedItems = products.filter{ $0.selected }
        let selectedNames = products.filter{ $0.selected }.map{ $0.name }
        print(selectedItems)
        print(selectedNames)
    }
struct Product {
    let name : String
    let value : String
    let img : String
    let id : Int

    var selected = false

    init(dict : [String:Any]) {
        self.name = dict["name"] as? String ?? ""
        self.value = dict["value"] as? String ?? ""
        self.img = dict["img"] as? String ?? ""
        self.id = dict["id"] as? Int ?? 0
    }
}

0 个答案:

没有答案