4

我有一个带有开关控制的表格视图。我的问题是:单击开关时如何检索行表ID?我可以检索开关状态,但不能检索 id

这是我获取开关状态的代码:

- (void)aggiungiTag:(id)sender {    
    NSLog(@"the tag value is: %d", [sender isOn]);
    return;
}

这是我将按钮开关控制到单元格的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    // Configure the cell...
    //inseriamo nelle celle la nostra lista
    cell.textLabel.text = [arrTagResidui objectAtIndex:indexPath.row];

    /*** aggiungo lo switch per i tag ***/
    //lo istanzio e setto la posizione
    UISwitch *switchObj = [[UISwitch alloc] initWithFrame:CGRectMake(1.0, 1.0, 20.0, 20.0)];
    //setto il valore di default
    switchObj.on = NO;
    //setto l'action ed i controlli degli eventi
    [switchObj addTarget:self action:@selector(aggiungiTag:) forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];
    //aggiungo lo switch alle celle
    cell.accessoryView = switchObj;

    NSInteger row = indexPath.row;
    [arrBoolSwitch insertObject:[NSNumber numberWithBool:NO] atIndex:row]; 
    [switchObj release];
    return cell;
}
4

3 回答 3

2

这一切都取决于您的表、代码等...但是如果您只是在寻找行,一种选择可能是将 的tag属性设置UISwitch为 indexPath.row (或您可以计算的某个值)。就像是:

[switchObj setTag:indexPath.row];

然后你会在你的方法中有行ID:

- (void)aggiungiTag:(id)sender {    
    NSLog(@"the tag value is: %d, row is %d", [sender isOn], [sender tag]);
    return;
}

这一切都取决于最终目标是什么以及应用程序的其余部分在做什么——但它既便宜又容易。

于 2010-12-09T19:48:18.067 回答
2

只需调整您的事件处理程序以接受事件参数:

- (void)aggiungiTag:(id)sender forEvent:(UIEvent*)event {    
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:
     [[[event touchesForView:sender] anyObject] locationInView:self.tableView]];
    // do stuff with indexPath
}

不要忘记更改 @selector 中的签名:

[switchObj addTarget:self 
              action:@selector(aggiungiTag::) // <-- two colons now :)
    forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];
于 2010-12-09T19:41:31.797 回答
0

这是运行的解决方案!;)

- (void)aggiungiTag:(id)sender {    

    //recupero l'oggetto switch di cui ho bisgno
    UISwitch *theSwitch = (UISwitch *)sender;

    //recupero la cella della tabella sulla quale è posizionato lo switch
    UITableViewCell *cell = (UITableViewCell *)theSwitch.superview;
    UITableView *tableView = (UITableView *)cell.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];

    NSLog(@"the row is: %d", indexPath.row);
    NSLog(@"the tag value is: %d", [theSwitch isOn])
}

谢谢大家!

于 2010-12-09T23:11:37.087 回答