butter_baby butter_baby - 7 months ago 71
Swift Question

Toggle radio button within a UITableViewCell

I am taking the index of the selected cell to display a selected radio button image. It works just fine, but once I attempt to select a cell that contains the selected radio button it will not deselect with the unselected radio button image:

if indexPath.row == self.selectedIndex {
cell.button.setImage(UIImage(named: "radio_selected"), forState: UIControlState.Normal)
} else {
cell.button.setImage(UIImage(named: "radio_unselected"), forState: UIControlState.Normal)

How could I revise this code so that I can toggle the image off and on when selecting the same cell?


In your didSelectRowAtIndexPath check for already selected cell

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
      if self.selectedIndex == indexPath.row {
          self.selectedIndex = -1
      else {
          self.selectedIndex = indexPath.row