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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With