Mohammed Yaseen Shah
Mohammed Yaseen Shah

Reputation: 35

How do I have a single select and a multiselect in my tableview?

in my cellForRowAt Im inflating my xib and setting its content:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! TableViewCell

    cell.label.text = data[indexPath.row]
    let tap = UIGestureRecognizer(target: self, action: #selector(tableCellTap(_:cell:)))
    cell.addGestureRecognizer(tap)

    cell.selectionStyle = .none
    cell.checkBox.isUserInteractionEnabled = false
    cell.checkBox.boxType = .circle

    cell.checkBox.markType = .radio
    cell.checkBox.cornerRadius = 0
    cell.checkBox.stateChangeAnimation = .expand(.fill)

    if (indexPath.row == selectedIndex){
        cell.checkBox.checkState = .checked
    }else{
        cell.checkBox.checkState = .unchecked
    }



    return cell
}

Then Im setting my deselect and select values

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

    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    cell.checkBox.checkState = .checked
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    cell.checkBox.checkState = .unchecked
}

I need a sense of direction in how i can make it select and deselect the same row and update my xib file checkbox? m13checkbox is being used when i click on the cell for the first time it selects it but when i click on the same cell again it does not call it and does nothing until a loop a completed in the checkboxes

Upvotes: 0

Views: 622

Answers (2)

sarosh mirza
sarosh mirza

Reputation: 702

you don't need didDeselectRowAt, you can achieve the same functionality by checking if the radio button is checked in your didSelectRowAt. If the radio button is checked, simply uncheck it and vice versa.

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

    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    if(cell.checkBox.isChecked){
        cell.checkBox.checkState = .unchecked   
    }else{
        cell.checkBox.checkState = .checked 
    }

}

Upvotes: 1

Adnan Ahmad
Adnan Ahmad

Reputation: 447

Apple has already given very good sample code for that on its website, you can check at:https://developer.apple.com/library/content/samplecode/TableMultiSelect/Introduction/Intro.html

Upvotes: 0

Related Questions