user3740845
user3740845

Reputation: 57

Swift Allow selection of only one cell

I have a working UITableview which currently allows multiple Cells to be selected. I would like just one to be selected and if a previous one was chosen then the new selection should uncheck the previous one. Mind bender! Here is my code:

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let indexPath = tableView.indexPathForSelectedRow();
    let CurrentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    if CurrentCell.imageView!.image == nil {
        let SelectedCell = CurrentCell.textLabel!.text
        CurrentCell.imageView!.image = UIImage(named:"check")!
        CurrentCell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
        println("Selected Cell is")
        println(SelectedCell)
    } else {
        CurrentCell.imageView!.image = nil
        let SelectedCell = "NothingSelected"
        CurrentCell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)    
        println("Nothing Selected")
    }
}

Upvotes: 1

Views: 6961

Answers (2)

vadian
vadian

Reputation: 285069

A very effective way to manage the selection state is to add a selected property to the data model, in this example just called Model

class Model {

  var selected = false

  ...
}

In the UITableViewController class we assume there is an Array data which holds the Model items as the data source for the table view.

var data = [Model]()

In cellForRowAtIndexPath set the image and text depending on the selected property:

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier") as! UITableViewCell
    let currentItem = data[indexPath.row]
    if currentItem.selected {
      cell.imageView!.image = UIImage(named:"check")!
      cell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
    } else {
      cell.imageView!.image = nil
      cell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
    }

    return cell
  }

In didSelectRowAtIndexPath set the property selected of the currently selected cells to false, set the property selected of the just selected cell to true and reload the table, the changes are applied in cellForRowAtIndexPath

  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    data.filter {$0.selected == true}.map {$0.selected = false}
    let currentItem = data[indexPath.row]
    currentItem.selected = true
    tableView.reloadData()
  }

Upvotes: 5

Eugene Braginets
Eugene Braginets

Reputation: 856

you can create your instance var to keep your selection index

and then in your cellForINdexPath method check if the current cell is equals to it:

that was discussed here: How to uncheck all rows using UITableViewCellAccessoryCheckmark

Upvotes: 0

Related Questions