stacks
stacks

Reputation: 67

uitableview with single selection and multiple selection

I have a tableview that has three sections.

Section 0, 1: Select one row in the section. Selected row gets a checkmark. Deselect and un-checkmark old selection if a new row is selected.

Section 2: Press one in this section for an automatic segue.


The problem is that when I press a row in Section 2, a checkmark appears and then it segues. I don't want the checkmark to appear at all, but I'm having a hard time finding a way to get rid of it.

I set self.tableView.allowsMultipleSelection = true in viewDidLoad so I can select a row in each section, which works great for the first two sections.

Then in cellForRowAt I set cell.accessoryType = .none for Section 2 (third section) so that I wouldn't get a checkmark for selecting a row in this section.

Doesn't seem to work though.


override func viewDidLoad() {
    self.tableView.allowsMultipleSelection = true
}

override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let section = indexPath.section
    switch section {
    case 0,1:
        if let selected = tableView.indexPathsForSelectedRows {
            for selectedIndexPath in selected {
                if selectedIndexPath.section == indexPath.section {
                    tableView.deselectRow(at: selectedIndexPath, animated: false)
                }
            }
        }
        return indexPath
    case 2:
        return indexPath
    default:
        return nil
    }
}



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FilterTableViewCell", for: indexPath) as! FilterTableViewCell
    let section = indexPath.section
    switch section {
    case 0:
        cell.theLabel.text = myDataStuff[indexPath.row]
    case 1:
        cell.theLabel.text = otherDataStuff[indexPath.row]
    case 2:
        cell.theLabel.text = lastDataStuff[indexPath.row]
        cell.accessoryType = .none
    default:
        break
    }
    return cell
}

Upvotes: 0

Views: 1591

Answers (1)

mrcfal
mrcfal

Reputation: 454

You might have something like this in your class FilterTableViewCell (maybe next time just share more code):

override func setSelected(_ selected: Bool, animated: Bool) {
    if selected {
        self.accessoryType = .checkmark
    }
    else {
        self.accessoryType = .none
    }
}

So, even though your rows in section 3 have accessoryType = .none, when you select them this property is modified again.

The quick solution is to use these functions to handle the checkmark instead of setSelected:

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

}

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

}

Upvotes: 1

Related Questions