单击开关时检索行表ID?

时间:2010-12-09 19:30:30

标签: iphone objective-c uitableview uiswitch

我有一个带开关控制的表格视图。我的问题是:当我点击开关时如何检索行表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;
}

3 个答案:

答案 0 :(得分: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)];

答案 1 :(得分:2)

这一切都取决于您的表格,代码等等......但如果您只是在寻找行,一个选项可能是将tag的{​​{1}}属性设置为indexPath.row(或者你可以计算的值)。类似的东西:

UISwitch

然后你的方法中会有行id:

[switchObj setTag:indexPath.row];

所有这些都取决于最终目标是什么以及应用程序的其余部分正在做什么 - 但它既便宜又简单。

答案 2 :(得分: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])
}

谢谢大家!