将事件侦听器直接添加到您的UISwitch
而不是依赖于didSelectRowAtIndexPath
.
-(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
// Here I assume you created a subclass MyCell of UITableViewCell
// And exposed a member named 'switch' that points to your UISwitch
MyCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[MyCell alloc] init];
cell.selectionStyle = UITableViewCellSelectionStyleNone; // This could be moved into MyCell class
[cell.switch addTarget:self action:@selector(switchChanged:) forControlEvent:UIControlEventValueChanged];
}
// Now we need some way to know which cell is associated with the switch
cell.switch.tag = indexPath.row;
}
现在要监听 swich 事件,在同一个类中添加这个方法
-(void)switchChanged:(UISwitch*)switch {
NSUInteger cellIndex = switch.tag;
...
}