gozdebal gozdebal - 1 year ago 119
iOS Question

Disabling Mutliple Row Selection in Tableview in Swift

I'm new to Swift and I want to disable multiple row selection in my tableview. I try to implement different type of approaches and my final code block is below, which is not working.
Thanks for your help.

override func viewDidLoad() {
super.viewDidLoad()
companyTableView.allowsMultipleSelection = false
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark;
}

tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}

tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) {
if selectedCells.contains(indexPath.row) {
selectedCells.remove(indexPath.row)
cell.accessoryType = .none
} else {
selectedCells.insert(indexPath.row)
cell.accessoryType = .checkmark
}
}
}

Answer Source

Please try this code:

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if !selectedCells.contains(indexPath){
            selectedCells.add(indexPath)

            if let cell = tableView.cellForRow(at: indexPath) {
                cell.accessoryType = .checkmark
            }
        }
    }


 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        if selectedCells.contains(indexPath){
            selectedCells.remove(indexPath)

            if let cell = tableView.cellForRow(at: indexPath) {
                cell.accessoryType = .none
            }
        }
    }

And in the cellForRowAt use this:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if selectedCells.contains(indexPath){
                cell.accessoryType = .checkmark
        }
        else{
            cell.accessoryType = .none
        }

        return cell
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download