getting the index path of a cell inside UITableViewCell in swift

could anyone tell me how to get the index of a cell inside its class which is uitableViewCell more specifically , inside an action function of UISwitch . I did the following..

        var cell = sender.superview?.superview as UITableViewCell
        var table: UITableView = cell.superview as UITableView
        let indexPath = table.indexPathForCell(cell)

but then it crashes. what is the solution ?

Upvotes: 2

Views: 9989

Answers (2)

JMFR
JMFR

Reputation: 809

You don't want to know the index path of the cell inside of the cell. The index path is an implementation detail of the UITableViewController. The cell should be an independent object.

What you really want to do is to assign an action to run when your switch is changed.

class MySwitchCell: UITableViewCell {

    @IBOutlet weak var switchCellLabel: UILabel!
    @IBOutlet weak var mySwitch: UISwitch!

    //Declare an action to be run
    var action: ((sender: UISwitch) -> Void)?
    //then run it
    @IBAction func switchAction(sender: UISwitch) {
        action?(sender: sender)
    }

}

Then give the action something to do when you configure the cell.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! MySwitchCell

        cell.switchCellLabel.text = items[indexPath.row]
        cell.mySwitch.on = NSUserDefaults.standardUserDefaults().boolForKey(items[indexPath.row])
        cell.action = { [weak self] sender in
            if let tableViewController = self {
                NSUserDefaults.standardUserDefaults().setBool(sender.on, forKey: tableViewController.items[indexPath.row]) }
        }
        return cell
    }

For example this one sets a bool in the NSUserDefaults based on the state of that switch.

You can checkout the whole sample project from https://github.com/regnerjr/SimpleCellSwitchAction

Upvotes: 0

Nishant
Nishant

Reputation: 12617

Try this:

Assuming you have a UISwitch *cellSwitch object in cell custom class

In cellForRowAtIndexPath:

cell.cellSwitch.tag = indexPath.row

In IBAction for this switch:

let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)

Upvotes: 3

Related Questions