我有一个UITableView,里面有自定义单元格。每个单元都有一个开关,每次交换开关时我都需要获取特定单元的indexPath。如何在每次交换开关时使用自定义单元格从UITableView返回单元格的indexPath?
答案 0 :(得分:8)
您可以使用indexPathForRowAtPoint
之类的:
@IBAction func switchChanged(sender: UIControl) {
let rowPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(rowPoint)
println(indexPath)
}
这是Objective C版
- (IBAction)toggleSwitch:(id)sender {
UISwitch *switchInCell = (UISwitch *)sender;
CGPoint pos = [switchInCell convertPoint:switch.bounds.origin toView:tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pos];
}
如果要在自定义单元格中获取单元格的indexPath:
// 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
}
答案 1 :(得分:0)
我能想到解决这个问题的一种方法是
编辑这可能适用于iOS6或更早版本
- (void)toggleSwitch:(id)sender {
UISwitch *switch = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) switch.superview;
NSIndexPath *indexpath = [[self yourTableView] indexPathForCell:cell];
}
答案 2 :(得分:0)
一节TableView:
在方法cellForRowAtIndexPath
中,您可以将当前单元格的标记设置为cell.switch.tag = indexPath.Row
,在切换方法中,您可以获取切换标记
- (void)toggleSwitch:(id)sender {
UISwitch *switch = (UISwitch *)sender;
int row = switch.tag;
//you can switch on the switch values to to get the exact switch then do your action
}
多个部分tableView:
创建一个具有属性NSIndexPath
的自定义切换类,然后在方法cellForRowAtIndexPath
中,您可以使用实际单元格的索引路径设置此属性,但不要忘记重置此属性自定义单元格中的prepareForReuse
方法。
在您的切换方法中,您将获得实际的indexPath