没有得到indexPath用于在UITableViewCell中点击UISwitch

时间:2012-04-04 10:42:06

标签: ios ios5 uitableview uiswitch

我在UITableViewCell中添加了一个UISwitch,表内容是动态的,这意味着tableview中可能有很多UISwitch,我需要为每个UITableViewCell获取UISwitch状态,但不能获得indexPath accessoryButtonTappedForRowWithIndexPath方法。

我的代码是:

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

1 个答案:

答案 0 :(得分:5)

控件事件应为UIControlEventValueChanged

不是UIControlEventTouchUpInside。改变它,然后再试一次。

因此动作设置声明应如下所示:

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

修改

- (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];
}