Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting indexPath from switch on UITableView

Tags:

ios

swift

I have a UITableView set up with custom cells in it. Each cell has a switch in it and I need to get the indexPath of a specific cell every time a switch is interacted with. How can I return the indexPath of a cell from a UITableView with custom cells each time a switch is interacted?

like image 665
ACR Avatar asked Dec 04 '25 09:12

ACR


1 Answers

You can use the indexPathForRowAtPoint like:

@IBAction func switchChanged(sender: UIControl) {
    let rowPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(rowPoint)
    println(indexPath)
}

This is the Objective C version

- (IBAction)toggleSwitch:(id)sender {
     UISwitch *switchInCell = (UISwitch *)sender;
     CGPoint pos = [switchInCell convertPoint:switch.bounds.origin toView:tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pos];
}

If you want to get the cell's indexPath in your custom cell:

// CustomCell.swift
@IBAction func switchChanged(sender: UIControl) {
    let tableView = self.tableView()
    let indexPath = tableView?.indexPathForCell(self) 
    println(indexPath)
}

func tableView() -> UITableView? {
    var tableView = self.superview
    while (tableView != nil && !(tableView is UITableView)) {
        tableView = tableView!.superview
    }

    return tableView as? UITableView
}
like image 188
Bannings Avatar answered Dec 06 '25 00:12

Bannings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!