Not getting indexPath for tapping UISwitch in a UITableViewCell

ios, ios5, uiswitch, uitableview

Solution

The control event should be `UIControlEventValueChanged`.

Not `UIControlEventTouchUpInside`. Change that and try again.

So the action setting statement should be as follows:

[useLocationSwitch addTarget: self
                      action: @selector(accessoryButtonTapped:withEvent:)
            forControlEvents: UIControlEventValueChanged];

Edit:

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    UISwitch *switch1 = (UISwitch *)button;
    UITableViewCell *cell = (UITableViewCell *)switch1.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

    //NSIndexPath * indexPath = [showLocationTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: showLocationTableView]];
    if ( indexPath == nil )
        return;

    [showLocationTableView.delegate tableView: showLocationTableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}

Problem

I added a UISwitch in a UITableViewCell, the table contents are dynamics, which means that there may be many UISwitches in a tableview, I need to get the UISwitch state for every UITableViewCell, but not getting the `indexPath` in `accessoryButtonTappedForRowWithIndexPath` method. my code is: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { LocationCell *cell = (LocationCell *)[tableView dequeueReusableCellWithIdentifier:@"LocationCell"]; UISwitch *useLocationSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; [cell addSubview:useLocationSwitch]; cell.accessoryView = useLocationSwitch; [useLocationSwitch addTarget: self action: @selector(accessoryButtonTapped:withEvent:) forControlEvents: UIControlEventTouchUpInside]; return cell; } - (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event { NSIndexPath * indexPath = [showLocationTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: showLocationTableView]]; if ( indexPath == nil ) return; [showLocationTableView.delegate tableView: showLocationTableView accessoryButtonTappedForRowWithIndexPath: indexPath]; } -(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{ NSLog(@"index path: %@", indexPath.row); } ```

Original source