Pages

Adding the checkmarks to the cell of the table view

As you know that cell's accessory can be of different type like details, details disclosure, disclosure indicator & checkmarks. As these are of different type then obviously they follow different purpose like if cell is of type detail disclosure then tapping on it will take you to new table view, disclosure indicator will lead you to more detail view of the same cell's data, check marked cell indicates that the particular option of the app in on/off. like in media player if shuffle is on/off or repeat is on/off etc. By using a check marked cell you can use particular cell as option to on/off this will perform an event. Lets see how you do it through code...


override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {        
        let selectedItem = items[indexPath.row]        
        selectionHandlerFromPopover?(selectedItem: selectedItem)
        dismissViewControllerAnimated(true, completion: nil)
                        //creating a new cell's object iff user selected a new cell
        var newCell = tableView.cellForRowAtIndexPath(indexPath)        
        if selectedItem == "shuffle" && newCell != nil && shufflingCounter == 0 {        
            shufflingCounter = 1
                    //setting the accessory type to the "Checkmark"
            newCell?.accessoryType = .Checkmark        
        } else if selectedItem == "shuffle" && newCell != nil && shufflingCounter == 1 {           
            shufflingCounter = 0
            tableView.deselectRowAtIndexPath(indexPath, animated: true)                                              //setting the accessory type to "None"
            newCell?.accessoryType = .None       

        } else if selectedItem == "repeat" && newCell != nil && repeatCounter == 0 {           
            repeatCounter = 1
            newCell?.accessoryType = .Checkmark        
        } else if selectedItem == "repeat" && newCell != nil && repeatCounter == 1 {            
            repeatCounter = 0
            tableView.deselectRowAtIndexPath(indexPath, animated: true)            newCell?.accessoryType = .None
        }
    }

Here in didSelectRowAtIndexPath() method all we are doing is getting the item that is checked in the table view cell && corresponding to it if it is "shuffle" or "repeat", corresponding to the previously if the cell is checked or not, we place a checkmark on it && the line of code that do this is:
              "newCell?.accessoryType = .Checkmark"
              "newCell?.accessoryType = .None"
Check marking the cell && undoing the checkmark. Here is output:

In this output "shuffle" cell is checked marked if you click it once && vanish if you click on it again.