在UITableViewCell中点击UISwitch无法获取indexPath

3

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

我的代码如下:

- (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个回答

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

仍然无法获取索引值。 - Firdous
我已经更新了我的答案。它还没有测试过。一旦我进入Mac机器,我会很快测试它(几分钟)。 - Ilanchezhian
是的,它已经测试过了,应该会给出预期的值。 - Ilanchezhian
在iOS 7中使用: CGPoint switchPositionPoint = [sender convertPoint:CGPointZero toView:[self tableView]]; NSIndexPath *indexPath = [[self tableView] indexPathForRowAtPoint:switchPositionPoint]; - user1872384

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接