3

我在一个UITableViewCell中添加了一个UISwitch,表格内容是动态的,也就是说一个tableview中可能有很多UISwitch,我需要获取每个UITableViewCell的UISwitch状态,但是没有获取到indexPathinaccessoryButtonTappedForRowWithIndexPath方法。

我的代码是:

- (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);
}
4

1 回答 1

5

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];
}
于 2012-04-04T10:48:05.107 回答