首页 > 解决方案 > 从 uiTableViewCell 更改选定单元格的检查状态

问题描述

我是 swift 新手,并试图更改选中的 tableviewcell。我试着; 用户选择城市和地区,然后单击保存按钮,应用程序将信息发送到服务器。所以那里没有问题。当用户想要更新城市或地区时,我应该在地区之前检查,用户可以看到他/她选择了什么。我正在使用 json 从服务器获取第一个信息并将它们附加到数组中。当用户单击更新按钮时,我可以在调试模式下看到所选信息之前,但不会检查 tableview 单元格。对不起,我的英语不好顺便说一句。

第一次选择我在做什么:

in viewDidLoad()
        self.tableViewDistrict.isEditing = true
        self.tableViewDistrict.allowsMultipleSelection = true
        self.tableViewDistrict.allowsMultipleSelectionDuringEditing = true

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectDeselectCell(tableView: tableView, indexPath: indexPath)
    }

extension ViewController{
    func selectDeselectCell(tableView: UITableView, indexPath: IndexPath){
        self.selectedDistId.removeAll()
        if let array = tableView.indexPathsForSelectedRows{
            for index in array{
                selectedDistId.append(districtArray[index.row].id!)
            }        
        }
    }
}

标签: swiftuitableview

解决方案


假设您已将所有先前选择的数据存储在一个数组中,例如

var alreadySelectedDistricts : [String] = []

所以在你的 cellForRowAt 方法中你可以做一个检查

for district in alreadySelectedDistricts { 
    if cell.districtLabel.text.contains(district) { 
        cell.accessoryType = .checkmark
    } else { 
        cell.accessoryType = .none
    }
}

推荐阅读